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

本文是小编为大家收集整理的关于返回在Flask中用FPDF生成的PDF的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

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

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数据输出作为字符串( dest='S' ) . 将输出编码为Latin-1 ,否则烧瓶将其编码为UTF-8,并且可能无效.设置Content-Disposition和Content-Type标题,以告诉浏览器下载/处理PDF文件.返回构造的响应.

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

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

本文地址:https://www.itbaoku.cn/post/2090915.html

问题描述

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

推荐答案

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.