首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >强制使用python在pyFPDF中添加新页面

强制使用python在pyFPDF中添加新页面
EN

Stack Overflow用户
提问于 2015-08-19 13:01:30
回答 1查看 1.1K关注 0票数 0

我使用pyFPDF模板生成pdf,但我想打印两页,不仅一个是可能的!例如:

代码语言:javascript
复制
elements = [
    { 'name': 'company_logo', 'type': 'I', 'x1': 20.0, 'y1': 17.0, 'x2': 78.0, 'y2': 30.0, 'font': None, 'size': 0.0, 'bold': 0, 'italic': 0, 'underline': 0, 'foreground': 0, 'background': 0, 'align': 'I', 'text': 'logo', 'priority': 2, },
    { 'name': 'company_name', 'type': 'T', 'x1': 17.0, 'y1': 32.5, 'x2': 115.0, 'y2': 37.5, 'font': 'Arial', 'size': 12.0, 'bold': 1, 'italic': 0, 'underline': 0, 'foreground': 0, 'background': 0, 'align': 'I', 'text': '', 'priority': 2, },
    { 'name': 'box', 'type': 'B', 'x1': 15.0, 'y1': 15.0, 'x2': 185.0, 'y2': 260.0, 'font': 'Arial', 'size': 0.0, 'bold': 0, 'italic': 0, 'underline': 0, 'foreground': 0, 'background': 0, 'align': 'I', 'text': None, 'priority': 0, },
    { 'name': 'box_x', 'type': 'B', 'x1': 95.0, 'y1': 15.0, 'x2': 105.0, 'y2': 25.0, 'font': 'Arial', 'size': 0.0, 'bold': 1, 'italic': 0, 'underline': 0, 'foreground': 0, 'background': 0, 'align': 'I', 'text': None, 'priority': 2, },
    { 'name': 'line1', 'type': 'L', 'x1': 100.0, 'y1': 25.0, 'x2': 100.0, 'y2': 57.0, 'font': 'Arial', 'size': 0, 'bold': 0, 'italic': 0, 'underline': 0, 'foreground': 0, 'background': 0, 'align': 'I', 'text': None, 'priority': 3, },
]
#here we instantiate the template and define the HEADER
f = Template(format="A4", elements=elements,
             title="Sample Invoice")
f.add_page()
#we FILL some of the fields of the template with the information we want
#note we access the elements treating the template instance as a "dict"
f["company_name"] = "Sample Company"
f["company_logo"] = "pyfpdf/tutorial/logo.png"

#and now we render the page
f.render("./template.pdf")

当我使用这种方法时,所有这些数据都会出现在相同的pdf中,我想在pdf的第二页上打印一些元素吗?我该怎么做,有什么帮助吗?!

EN

回答 1

Stack Overflow用户

发布于 2015-11-28 21:57:30

您可以在两个不同的列表(elements1、elements2)中分离元素,并在不同的模板中使用每个元素,并使用PyPDF2合并它们。

代码语言:javascript
复制
f1 = Template(format="A4", elements=elements1,
         title="Sample Invoice")

f2 = Template(format="A4", elements=elements2,
         title="Sample Invoice")

from PyPDF2 import PdfFileMerger, PdfFileReader
from StringIO import StringIO

page1 = StringIO()
page2 = StringIO()
final_pdf = StringIO()

page1.write(f1.render('doc1.pdf',dest='S'))
page2.write(f2.render('doc2.pdf',dest='S'))

pages = [ PdfFileReader(page1), PdfFileReader(page2) ]
pdf_merger = PdfFileMerger()

for page in pages:
    pdf_merger.append(page)

pdf_merger.write(final_pdf)

您可以从final_pdf.getvalue().获得最终输出

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32096284

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档