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

时间:2018-05-25 15:04:10

标签: python pdf 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有更聪明的方法吗?

1 个答案:

答案 0 :(得分:2)

一种选择是使用reportlab提供的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']),])

第二种方法是将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()