使用 reportlab 在流程中编写多行文本

Bas*_*asj 6 python pdf reportlab

这适用于在 PDF 文件中写入文本reportlab

from reportlab.pdfgen import canvas
from reportlab.lib.units import cm

c = canvas.Canvas("test.pdf")
c.drawString(1 * cm, 29.7 * cm - 1 * cm, "Hello")
c.save()
Run Code Online (Sandbox Code Playgroud)

但是在处理多行文本时,不得不处理x, y每一行的坐标是很不愉快的:

text = "Hello\nThis is a multiline text\nHere we have to handle line height manually\nAnd check that every line uses not more than pagewidth"
c = canvas.Canvas("test.pdf")

for i, line in enumerate(text.splitlines()):
    c.drawString(1 * cm, 29.7 * cm - 1 * cm - i * cm, line)

c.save()
Run Code Online (Sandbox Code Playgroud)

有没有更聪明的方法来做到这一点reportlab

Jor*_*ley 13

一种选择是使用 reportlab 提供的 Flowables,一种类型的 Flowable 元素是Paragraph. 段落支持<br>作为换行符。

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Paragraph
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import cm

my_text = "Hello\nThis is a multiline text\nHere we do not have to handle the positioning of each line manually"

doc = SimpleDocTemplate("example_flowable.pdf",pagesize=A4,
                        rightMargin=2*cm,leftMargin=2*cm,
                        topMargin=2*cm,bottomMargin=2*cm)

doc.build([Paragraph(my_text.replace("\n", "<br />"), getSampleStyleSheet()['Normal']),])
Run Code Online (Sandbox Code Playgroud)

第二种选择是drawText与 a一起使用TextObject

c = canvas.Canvas("test.pdf")
textobject = c.beginText(2*cm, 29.7 * cm - 2 * cm)
for line in my_text.splitlines(False):
    textobject.textLine(line.rstrip())
c.drawText(textobject)
c.save()
Run Code Online (Sandbox Code Playgroud)