簡體   English   中英

如何合並兩個比薩文件

[英]How to merge two pisaDocument file

我如何使用xhtml2pdf附加兩個“ pisaContext”對象python。

我的要求是將兩個頁面分別呈現為2個不同的pdf,然后合並返回合並的pdf。

我知道這是一個老問題,但今天我遇到了這個問題,這是我使用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")

基本上,我使用呈現在內存中兩個pisaDocuments StringIO並傳遞給PdfFileMergerappend方法,最后寫了一個名為“files_merged.pdf”文件。 您還可以傳遞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