返回在Flask中使用FPDF生成的PDF [英] Return PDF generated with FPDF in Flask

查看:333
本文介绍了返回在Flask中使用FPDF生成的PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用以下代码生成带有图像的PDF.如何从Flask路线返回生成的PDF?

I can generate a PDF with an image using the code below. How can I return the generated PDF from a Flask route?

from fpdf import FPDF
pdf = FPDF()
img = input('enter file name')
g = img + '.jpg'
pdf.add_page()
pdf.image(g, 50, 50)
pdf.output(img + '.pdf', 'F')

推荐答案

使用 make_response 以将PDF数据输出作为字符串来创建响应(将输出编码为latin-1 ,否则Flask会将其编码为UTF-8,并且可能无效.设置Content-DispositionContent-Type标头,以告知浏览器下载/处理PDF文件.返回构造的响应.

Use make_response to create a response with the PDF data output as a string (dest='S'). Encode the output as latin-1, otherwise Flask will encode it as UTF-8 and it may not be valid. Set the Content-Disposition and Content-Type headers to tell the browser to download/handle a PDF file. Return the constructed response.

from flask import make_response

@app.route('/jpg_to_pdf/<name>')
def jpg_to_pdf(name):
    pdf = FPDF()
    pdf.add_page()
    pdf.image(os.path.join(app.instance_path, name + '.jpg'), 50, 50)
    response = make_response(pdf.output(dest='S').encode('latin-1'))
    response.headers.set('Content-Disposition', 'attachment', filename=name + '.pdf')
    response.headers.set('Content-Type', 'application/pdf')
    return response

此示例假定图像位于实例文件夹中,请根据需要进行修改以指向图像实际所在的位置.

This example assumes the images are in the instance folder, modify as necessary to point to where the images actually are.

这篇关于返回在Flask中使用FPDF生成的PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆