Skip to content

Instantly share code, notes, and snippets.

@philfreo
Created June 21, 2013 22:50
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save philfreo/5834912 to your computer and use it in GitHub Desktop.
Save philfreo/5834912 to your computer and use it in GitHub Desktop.
A Flask view that returns HTML or generates a PDF
import mimerender
mimerender.register_mime('pdf', ('application/pdf',))
mimerender = mimerender.FlaskMimeRender(global_charset='UTF-8')
def render_pdf(html):
from xhtml2pdf import pisa
from cStringIO import StringIO
pdf = StringIO()
pisa.CreatePDF(StringIO(html.encode('utf-8')), pdf)
resp = pdf.getvalue()
pdf.close()
return resp
@app.route('/invoice/<invoice_id>/', methods=['GET'])
@login_required
@mimerender(default='html', html=lambda html: html, pdf=render_pdf, override_input_key='format')
def view_invoice(org_id, invoice_id):
html = render_template('invoice.html', id=invoice_id)
return { 'html': html } # mimerender requires a dict
@nmiguelmoura
Copy link

Hi,
Thanks for the code, I was looking for something like this.
But I could use some help, if you don't mind. When I run this code, I only get an html page instead of a PDF. Is there a way to open a pdf instead? Not creating the file, but opening it in the browser window.
Thanks in advance,
Nuno

@6LYTH3
Copy link

6LYTH3 commented Dec 11, 2017

@nmiguelmoura
Just make response like this

    pisa.CreatePDF(StringIO(html.encode('utf-8')), pdf)
    response = make_response(pdf.getvalue())
    response.headers['Content-Type'] = 'application/pdf'
    response.headers['Content-Disposition'] = 'inline; filenam=export.pdf'
    pdf.close()
    return response

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment