-
-
Save dario61081/12c6d9b3631c1f9fce7a6a7b9d69eadd to your computer and use it in GitHub Desktop.
A Flask view that returns HTML or generates a PDF
This file contains hidden or 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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment