使用 reportlab 在流中写入多行文本

Write multiple lines of text in a flow with reportlab

这可以用 reportlab:

在 PDF 文件中写入文本
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()

但是在处理多行文本时,不得不处理每一行的 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()

reportlab有没有更聪明的方法?

一种选择是使用reportlab提供的Flowables,一种可流动元素是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']),])

第二种选择是使用 drawTextTextObject:

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()