I generate a PDF file using PyFPDF library and would like to return this in-memory buffer without writing it to local disk.
@app.post("/pdf")
def generate_report(id_worker: int = Form(...), start_date: date = Form(...), end_date: date = Form(...)):
user = [id_worker]
start_date = datetime(start_date.year, start_date.month, start_date.day)
end_date = datetime(end_date.year, end_date.month, end_date.day)
attendance = filter_by_date(zk, user, start_date, end_date)
user_history = attendance_to_dict(attendance)
dates, data, days, errors, updated_history = data_to_july(user_history, start_date, end_date)
pdf = create_user_pdf(updated_history, start_date, end_date, days, errors)
pdf_temp = "attendance.pdf"
pdf.output(pdf_temp)
name = "report.pdf"
return FileResponse(pdf_temp, media_type="application/pdf", filename=name)
I've tried the following; however, without success:
name = "report.pdf"
pdf_buff = io.BytesIO()
pdf.output(pdf_buff)
pdf_buff.seek(0)
return FileResponse(pdf_buff.getvalue(), media_type="application/pdf", filename=name)
Is there a way to do this?
I made it work with this.
I used @Chris' suggestion fastapi from buffer, fpdf to bytes and encoding fpdf to make everything work