使用 Python Flask 将 html 转换为 pdf

Ola*_*ale 2 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
Run Code Online (Sandbox Code Playgroud)

我像这样在 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
Run Code Online (Sandbox Code Playgroud)

但它抛出这个错误

AttributeError: StringIO instance has no __call__ method
Run Code Online (Sandbox Code Playgroud)

Rob*_*obᵩ 5

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

  • Pdf.render_pdf() now returns pdf.getvalue(), a str.
  • view_invoice() now returns a tuple, so that the Content-Type header can be set.

 

#!/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)
Run Code Online (Sandbox Code Playgroud)