对于我的项目,我从另一个程序获得了一个纯文本文件 (report.txt)。它全部采用纯文本格式。如果您在记事本中打开它,它看起来不错(与纯文本文件一样多)。当我在 Word 中打开文件并显示段落时,我看到...表示空格,而向后的 P 表示段落。
我需要将此文件转换为 PDF 并添加一些其他 PDF 页面以生成最终的 PDF。所有这一切都发生在 Python 中。
我在将 report.txt 转换为 pdf 时遇到问题。我有 ReportLab,并且能够读取文件并进行一些更改(例如将文本更改为 Courier),但间距丢失了。读取文件时,它似乎会去除所有多余的空格。
问题: a) 是否有更简单的方法将 report.txt 转换为 pdf? b) 如果没有,有没有办法在我读取文件时保留我的空间? c) 还是我的段落样式中遗漏了一个可以保持原始外观的参数?
这是我的代码:
# ------------------------------------
# Styles
# ------------------------------------
styleSheet = getSampleStyleSheet()
mystyle = ParagraphStyle(name='normal',fontName='Courier',
fontSize=10,
alignment=TA_JUSTIFY,
leading=1.2*12,
parent=styleSheet['Normal'])
#=====================================================================================
model_report = 'report.txt'
# Create document for writing to pdf
doc = SimpleDocTemplate(str(pdfPath), \
rightMargin=40, leftMargin=40, \
topMargin=40, bottomMargin=25, \
pageSize=A4)
doc.pagesize = portrait(A4)
# Container for 'Flowable' objects
elements = []
# Open the model report
infile = file(model_report).read()
report_paragraphs = infile.split("\n")
for para in report_paragraphs:
para1 = '<font face="Courier" >%s</font>' % para
elements.append(Paragraph(para1, style=mystyle))
doc.build(elements)
最佳答案
我创建了一个小的辅助函数,通过使用等宽字体将多行文本转换为“报告外观”的 PDF 文件。太长的行在空格处换行,以适应页面宽度:
import textwrap
from fpdf import FPDF
def text_to_pdf(text, filename):
a4_width_mm = 210
pt_to_mm = 0.35
fontsize_pt = 10
fontsize_mm = fontsize_pt * pt_to_mm
margin_bottom_mm = 10
character_width_mm = 7 * pt_to_mm
width_text = a4_width_mm / character_width_mm
pdf = FPDF(orientation='P', unit='mm', format='A4')
pdf.set_auto_page_break(True, margin=margin_bottom_mm)
pdf.add_page()
pdf.set_font(family='Courier', size=fontsize_pt)
splitted = text.split('\n')
for line in splitted:
lines = textwrap.wrap(line, width_text)
if len(lines) == 0:
pdf.ln()
for wrap in lines:
pdf.cell(0, fontsize_mm, wrap, ln=1)
pdf.output(filename, 'F')
下面是使用此函数将文本文件转换为 PDF 文件的方式:
input_filename = 'test.txt'
output_filename = 'output.pdf'
file = open(input_filename)
text = file.read()
file.close()
text_to_pdf(text, output_filename)
关于python - 在 Python 中将纯文本转换为 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10112244/