gpt4 book ai didi

python - 使用 Python Flask 将 html 转换为 pdf

转载 作者:太空宇宙 更新时间:2023-11-04 03:17:58 27 4
gpt4 key购买 nike

这是我在 myclass.py 中的代码

class Pdf():

def render_pdf(self,name,html):


from xhtml2pdf import pisa
from StringIO import StringIO

pdf = StringIO()

pisa.CreatePDF(StringIO(html), pdf)

return pdf

我在 api.py 中这样调用它

@app.route('/invoice/<business_name>/<tin>', methods=['GET'])
def view_invoice(business_name,tin):

#pdf = StringIO()
html = render_template('certificate.html', business_name=business_name,tin=tin)
file_class = Pdf()
pdf = file_class.render_pdf(business_name,html)
return pdf

但是它抛出这个错误

AttributeError: StringIO instance has no __call__ method

最佳答案

以下脚本对我来说效果很好。请注意我所做的更改:

  • Pdf.render_pdf() 现在返回 pdf.getvalue(),一个 str
  • view_invoice() 现在返回一个元组,以便可以设置 Content-Type header 。

#!/usr/bin/env python

from flask import Flask, render_template
app = Flask(__name__)


class Pdf():

def render_pdf(self, name, html):

from xhtml2pdf import pisa
from StringIO import StringIO

pdf = StringIO()

pisa.CreatePDF(StringIO(html), pdf)

return pdf.getvalue()


@app.route('/invoice/<business_name>/<tin>', methods=['GET'])
def view_invoice(business_name, tin):

#pdf = StringIO()
html = render_template(
'certificate.html', business_name=business_name, tin=tin)
file_class = Pdf()
pdf = file_class.render_pdf(business_name, html)
headers = {
'content-type': 'application.pdf',
'content-disposition': 'attachment; filename=certificate.pdf'}
return pdf, 200, headers


if __name__ == '__main__':
app.run(debug=True)

关于python - 使用 Python Flask 将 html 转换为 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35608938/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com