使用reportlab在流程中编写多行文本 [英] Write multiple lines of text in a flow with reportlab
本文介绍了使用reportlab在流程中编写多行文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这可以使用reportlab
在PDF文件中写入文本:
This works to write a text in a PDF file with 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()
但是在处理多行文本时,必须处理每行新行的x, y
坐标是不愉快的:
but when dealing with multiple lines of text, it's unpleasant to have to handle the x, y
coordinate of each new line:
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
可以更聪明地做到这一点吗?
Is there a more clever way to do this with reportlab
?
推荐答案
一种选择是使用reportlab提供的Flowable,一种可流动元素是Paragraph
.段落支持<br>
作为换行符.
One option is to use the Flowables that reportlab provides, one type of flowable element is a Paragraph
. Paragraphs support <br>
as line breaks.
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']),])
第二种选择是将drawText
与TextObject
一起使用:
A second option is to use drawText
with 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()
这篇关于使用reportlab在流程中编写多行文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文