Created
June 21, 2013 22:50
A Flask view that returns HTML or generates a PDF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
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
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