[英]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提供的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']),])
第二種選擇是將drawText
與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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.