Serving dynamic PDF through Flask, generated with pdfrw Serving dynamic PDF through Flask, generated with pdfrw flask flask

Serving dynamic PDF through Flask, generated with pdfrw


Assuming you don't want to save the PDF to the server, and just keep it in memory, then serve it with Flask's send_file function, you could modify your write_fillable_pdf function to instead return a bytes type object. So instead of:

pdfrw.PdfWriter().write(output_pdf_path, template_pdf)

You could do the following:

buf = io.BytesIO()pdfrw.PdfWriter().write(buf, template_pdf)buf.seek(0)return buf

remembering to import io at the top of the file!

Then in your flask code, the return value of write_fillable_pdf could be passed directly to the send file function:

from flask import send_filedata = write_fillable_pdf() # With some argumentsreturn send_file(data, mimetype='application/pdf')

You'd probably want to modifiy the arguments write_fillable_pdf accepts, as you no longer wish to supply the output_pdf_path. You'd also want to pass this your data_dict which could be constructed based on values supplied from the user or somewhere else.