简体   繁体   English

如何合并两个比萨文件

[英]How to merge two pisaDocument file

Using xhtml2pdf how can i append two 'pisaContext' object python. 我如何使用xhtml2pdf附加两个“ pisaContext”对象python。

My requirement is to render two pages separately into 2 different pdf, and then merge return the merged pdf. 我的要求是将两个页面分别呈现为2个不同的pdf,然后合并返回合并的pdf。

I know that is a old question but I face this problem today, here is my solution using PyPDF2: 我知道这是一个老问题,但今天我遇到了这个问题,这是我使用PyPDF2的解决方案:

from StringIO import StringIO
from xhtml2pdf import pisa
from PyPDF2 import PdfFileMerger

# html1 and html2 are strings with the html content.
# link_callback is a function that return the path of files requested in the PDF file


pdf1_file = StringIO()
pdf1 = pisa.pisaDocument(
    StringIO(html1.encode('UTF-8')),
    pdf1_file,
    link_callback=link_callback,
    encoding='UTF-8'
)

pdf2_file = StringIO()
pdf2 = pisa.pisaDocument(
    StringIO(html2.encode('UTF-8')),
    pdf2_file,
    link_callback=link_callback,
    encoding='UTF-8'
)

if not pdf1.err and not pdf2.err:
    merger = PdfFileMerger()
    merger.append(pdf1_file)
    merger.append(pdf2_file)
    merger.write("files_merged.pdf")

Basically, I render the two pisaDocuments in memory using StringIO and pass them to PdfFileMerger with the append method and finally, write to a file named "files_merged.pdf". 基本上,我使用呈现在内存中两个pisaDocuments StringIO并传递给PdfFileMergerappend方法,最后写了一个名为“files_merged.pdf”文件。 You can also pass a StringIO instance to write method and do everything in memory: 您还可以传递StringIO实例以write方法并在内存中执行所有操作:

if not pdf1.err and not pdf2.err:
    merger = PdfFileMerger()
    merger.append(pdf1_file)
    merger.append(pdf2_file)
    output = StringIO()
    merger.write(output)
    file_content = output.getvalue()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM