使用Python Flask将html转换为pdf

时间:2016-02-24 17:25:14

标签: python flask

这是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

1 个答案:

答案 0 :(得分:2)

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

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

#!/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)