I have a view that contains a wizard form. When the form is submitted, a httpresponse is sent with a PDF file. I generate the PDF file with the FPDF2 Library from the data got in the form submitted by the user.
To be sure that the PDF class using this library works, I tested it in a simple python script.
My problem comes from the pdf that I download, I can not open it because no data is stored in it. I open it with the "Note" software and there is just an "None" written inside.
So how can I send the data of the pdf object to the Httpresponse ?
Here is my code :
class FormWizardQR(SessionWizardView):
template_name = "invoices/qr.html"
form_list = [FormStepOneBeneficiary, FormStepTwoPaymentInfos, FormStepThreeDebtor]
def done(self, form_list, **kwargs):
# GET DATA FROM FORMS
form_data = dict(ChainMap(*[form.cleaned_data for form in form_list]))
# PREPARE DATA FOR QR-PDF GENERATOR
list_str_pay_to = []
list_str_pay_by = []
reference = form_data.get('ref_number')
pdf = PDF('portrait', 'mm', 'A4')
pdf.set_margins(left=0, top=0, right=0)
pdf.add_page()
pdf.border_bill()
pdf.r_title("Récépissé")
pdf.r_zone_indications(reference=reference, list_str_pay_to=list_str_pay_to, list_str_pay_by=list_str_pay_by)
pdf.output(name="myfilename.pdf", dest="S")
print(type(pdf))
print(pdf)
response = HttpResponse(pdf, content_type='application/pdf')
response['Content-Disposition'] = "attachment; filename=myfilename.pdf"
return response
Thank you
According to the documentation of the last version of pyFPDF2 (version 2.5.7) : https://pyfpdf.github.io/fpdf2/fpdf/fpdf.html#fpdf.fpdf.FPDF.output
The dest is DEPRECATED and "By default the bytearray buffer is returned. If a name is given, the PDF is written to a new file."
So it just needs :
response = HttpResponse(bytes(pdf.output()), content_type='application/pdf')
response['Content-Disposition'] = "attachment; filename=myfilename.pdf"
return response