Skip to main content
 首页 » 编程设计

python之PDF 响应在 Python 3 中损坏但在 Python 2 中有效

2025年05月04日7jirigala

我用 python2.7 和 Flask 写了一个可以工作的应用程序。它所做的其中一件事是下载 PDF 发票。一切正常。

现在我正在做一个新的应用程序,它也允许下载 PDF 发票,但这次我使用的是 Python3。我可以将文件保存到服务器并获得完美工作的 PDF,但如果我尝试将其发送到浏览器,生成的文件已损坏。

这里是下载函数:

@mod.route('/get_invoice/<invoice_id>') 
def get_invoice(invoice_id): 
    invoice = Invoices.query.filter_by(id=invoice_id).all() 
 
    pdf_generator = PDFInvoice(invoice) 
    pdf = pdf_generator.new() 
 
    response = make_response(pdf.output(dest='S')) 
    response.headers['Content-Disposition'] = 'attachment; filename="invoice.pdf"' 
    response.headers['Content-Type'] = 'application/pdf' 
 
    return response 

这与旧的 Python2.7 应用程序中的工作函数几乎相同。

为了扩展,它正在打开这个(工作 PDF):

x�3R��2�35W(�r 
Q�w3T��30P^HISp^M^A�^X^[�^YZ*�^[^Z�^Y�*��(h�e^Vg�(�^V+$�(����e����奖h*�d��^@^@�v^T� 

进入此(损坏的 PDF):

x^Ü3Rðâ2Ð35W(çr 
QÐw3T°Ô30P^HISp^M^A^É^X^[è^YZ*^Ø^[^Zê^Y^Û*^Ĥ(h^Äe^Vg^Ö(^Ô^V+$^Ö(^Ô^×^×ëe§æ^Õèå¥^Öh*^Äd^Áô^@^@øv^T 

pdf 的其余数据是文本字符串,它们似乎没有变化。所以这似乎是某个地方的编码问题。

请您参考如下方法:

FPDF 输出一个 str,在 Python 2 中基本上等同于 bytes,但在 Python 3 中是 unicode,而不是字节。 Straight from the docs:

If you are using Python 3.x you have to use pdf.output(dest='S').encode('latin-1') in order to get the output, if you don't do so the generated PDF will be invalid