Skip to main content
 首页 » 编程设计

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

2024年10月24日9softidea

这是我在 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)