Oladapo Adebowale
Oladapo Adebowale

Reputation: 59

Converting html to pdf using Python Flask

Here is my code in 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

And I am calling it in api.py like this

@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

But it throws this error

AttributeError: StringIO instance has no __call__ method

Upvotes: 2

Views: 4442

Answers (1)

Robᵩ
Robᵩ

Reputation: 168596

The following script worked well for me. Note the changes I made:

  • 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)

Upvotes: 6

Related Questions