如何将文本写入 pdf 文件

lad*_*ads 3 pdf python-3.x

我正在使用Python3,我有一个很长的文本文件,我想创建一个新的pdf并在里面写入文本。

我尝试使用reportlab,但它只写一行。

from reportlab.pdfgen pdfgen import canvas

c = canvas.Canvas("hello.pdf")
c.drawString(100,750, text)
c.save()
Run Code Online (Sandbox Code Playgroud)

我知道我可以告诉它在哪一行写什么。但是有没有一个库,我可以只提供文本和页边距,然后它会将其写入 pdf 文件中?

谢谢

编辑:

或者我也可以使用一个可以轻松将 txt 文件转换为 pdf 文件的库?

Vis*_*ngh 6

仅仅在画布上绘制字符串并不能完成您的工作。
如果它只是原始文本,并且您不需要对文本进行任何修改,例如标题和其他类型的内容,那么您可以简单地将文本放入Flowablesie中Paragraph,并且Flowables可以将您的文本附加到story[].
您可以根据您的用途调整边距。

from reportlab.platypus import SimpleDocTemplate, Paragraph
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch
from reportlab.lib.pagesizes import letter


styles = getSampleStyleSheet()
styleN = styles['Normal']
styleH = styles['Heading1']
story = []

pdf_name = 'your_pdf_file.pdf'
doc = SimpleDocTemplate(
    pdf_name,
    pagesize=letter,
    bottomMargin=.4 * inch,
    topMargin=.6 * inch,
    rightMargin=.8 * inch,
    leftMargin=.8 * inch)

with open("your_text_file.txt", "r") as txt_file:
    text_content = txt_file.read()

P = Paragraph(text_content, styleN)
story.append(P)

doc.build(
    story,
)
Run Code Online (Sandbox Code Playgroud)

有关 Flowables 的更多信息,请阅读reportlab-userguide