【问题标题】:Write multiple lines of text in a flow with reportlab使用 reportlab 在流中编写多行文本
【发布时间】:2018-11-05 00:37:30
【问题描述】:

这可以用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?

【问题讨论】:

  • @JoranBeasley:用<br /> 替换\n 是不够的;似乎必须引入 Paragraph 类等。所以这个问题在某种意义上是不同的,它询问我们是否必须引入像 Paragraph 这样的布局系统,或者是否有其他选项。
  • 好吧,你问了关于流的问题……而段落是可流动的……drawString 不是可流动的……如果你觉得它不能解决你的问题,我可以重新打开它
  • 我仍然不确定它怎么不是 stackoverflow.com/questions/3816006/… 的骗子......但为你重新打开了

标签: python pdf reportlab


【解决方案1】:

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

第二种选择是使用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()

【讨论】:

  • 一个小细节@JoranBeasley 和第二个选项:textobject = c.beginText(2 * cm, 29.7 * cm - 2 * cm) 不是在页面顶部 2 厘米处开始文本,而是在 top of page + 2 cm - lineheight,为什么?
  • 第二个选项非常适合我的用例,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-29
相关资源
最近更新 更多