【问题标题】:Force add new page in pyFPDF using python使用 python 强制在 pyFPDF 中添加新页面
【发布时间】:2015-11-12 19:10:56
【问题描述】:

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

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 的第二页上?我该怎么做,有什么帮助吗?!

【问题讨论】:

    标签: python-2.7 pdf pdf-generation fpdf


    【解决方案1】:

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

    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() 获得最终输出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-11
      • 1970-01-01
      相关资源
      最近更新 更多