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

2024-04-29 15:03:14 发布

您现在位置:Python中文网/ 问答频道 /正文

这将使用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坐标是不愉快的:

^{pr2}$

有没有更聪明的方法来处理reportlab


Tags: 文件fromtest文本importpdflibcm
1条回答
网友
1楼 · 发布于 2024-04-29 15:03:14

一种选择是使用reportlab提供的流式元素,其中一种类型的流式元素是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一起使用:

^{pr2}$

相关问题 更多 >