使用Flask下载ReportLab PDF - Python

时间:2015-11-19 20:01:14

标签: python python-2.7 pdf flask reportlab

我有一个生成PDF的功能,我有一个Flask网站。我想将两者结合起来,以便在您访问该网站时生成并下载PDF。我正在努力组合我不完全理解的各种代码。生成并下载PDF但在尝试打开时无法加载。我错过了什么?

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

1 个答案:

答案 0 :(得分:6)

您可以使用Flask的send_file来提供文件:

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

使用as_attachment=True,您可以强制客户端下载文件,而不是在浏览器中查看文件。