Return PDF generated with FPDF in Flask
flask, fpdf, python
Solution
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.
Problem
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') ```