如何在reportlab中手动将新页面添加到PDF文档?

Posted

技术标签:

【中文标题】如何在reportlab中手动将新页面添加到PDF文档?【英文标题】:How to manually add a new page to a PDF document in reportlab? 【发布时间】:2020-12-05 16:40:52 【问题描述】:

我正在尝试使用 Python 3 和 reportlab 手动创建页面并将其添加到 PDF 文件中。

我可以轻松地创建第一页,并在上面绘图。但我不知道如何手动添加新页面。

例子:

from reportlab.pdfgen.canvas import Canvas
canvas = Canvas(pdf_path, pagesize=(WIDTH_OF_PAGE1,HEIGHT_OF_PAGE1))    
canvas.rect(100,100,200,200,fill=1, stroke=1) # draw on the first page, this is just an example...
# Now create and add a new page here, but how???
canvas2.rect(200,200,300,300,fill=1, stroke=1) # draw on the second page, this is just an example...
# Finally, save the PDF
canvas.save()

如何开始一个特定大小的新页面?

请注意,我没有使用鸭嘴兽。这些页面没有固定的高度。每个页面都有不同的高度,这是由某种算法预先计算的。所以这里不能使用“flowables”的概念,我需要在PDF文档中添加特定(不同)大小的页面。

解决方法是为每个页面创建一个单独的 PDF 文件,然后将它们与外部程序连接起来,但我不喜欢这个想法。

【问题讨论】:

【参考方案1】:

最后,我想出了如何创建一个新页面。在reportlab文档中提到过,我只是没有注意到。

canvas.showPage() #Close the current page and possibly start on a new page.

还有一个解决方案可以更改单个页面的页面大小 - 这是 Platypus 无法做到的:

canvas.showPage() # Close the current page and possibly start on a new page.
canvas.setPageSize(A3) # Change size of the current page

【讨论】:

以上是关于如何在reportlab中手动将新页面添加到PDF文档?的主要内容,如果未能解决你的问题,请参考以下文章

Python:如何使 Reportlab 在 PDF 输出中移至下一页

Reportlab:如何为 pdf 文件添加页脚

打印到 PDF Django & ReportLab

使用 Reportlab 的多个页面 - Django

Reportlab:条形码未绘制在 PDF 文件的顶部

Reportlab:如何在纵向和横向之间切换?