Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading ReportLab PDF with Flask - Python

I have a function which generates a PDF and I have a Flask website. I would like to combine the two so that when you visit the site, a PDF is generated and downloaded. I am working on combining various bits of code that I don't fully understand. The PDF is generated and downloaded but fails to ever load when I try to open it. What am I missing?

import cStringIO
from reportlab.lib.enums import TA_JUSTIFY
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from flask import make_response, Flask
from reportlab.pdfgen import canvas

app = Flask(__name__)
@app.route('/')
def pdf():

    output = cStringIO.StringIO()
    doc = SimpleDocTemplate("test.pdf",pagesize=letter)
    Story=[]

    styles=getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
    ptext = '<font size=12>test</font>'

    Story.append(Paragraph(ptext, styles["Justify"]))

    doc.build(Story)
    pdf_out = output.getvalue()
    output.close()

    response = make_response(pdf_out)
    response.headers['Content-Disposition'] = "attachment; filename='test.pdf"
    response.mimetype = 'application/pdf'
    return response
app.run()
like image 388
user2242044 Avatar asked Oct 25 '25 20:10

user2242044


1 Answers

You can use Flask's send_file for serving files:

from Flask import send_file
return send_file('test.pdf', as_attachment=True)

With as_attachment=True you can force the client to download the file instead of viewing it inside the browser.

like image 167
Dauros Avatar answered Oct 28 '25 09:10

Dauros