Django admin action to download multiple pdfs

I have been trying to make custom Django admin action that allows me to convert html page to pdf and then download that pdf, for each object separately if more than once is selected. and since there is only one request to be sent I know there will be only one response. So I tried to put these pdfs in a zip file and then download the zip.. but What I see at the end is corrupted zip file. No idea where is the problem

CODE in admin.py

def report_pdf(self, request, queryset):
    from django.template.loader import get_template
    from xhtml2pdf import pisa
    import tempfile
    import zipfile

    with tempfile.SpooledTemporaryFile() as tmp:
            with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED) as archive:
                for item in enumerate(queryset):
                    context = {"transactions": item}
                    template_path = "test-pdf.html"
                    template = get_template(template_path)
                    html = template.render(context)
                    file = open('test.pdf', "w+b")
                    pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file,
                                                encoding='utf-8')
                    file.seek(0)
                    pdf = file.read()
                    print(pdf)
                    file.close()
                    fileNameInZip = f"{item.chp_reference}.zip"
                    archive.writestr(fileNameInZip, pdf)
                tmp.seek(0)
                response = HttpResponse(tmp.read(), content_type='application/x-zip-compressed')
                response['Content-Disposition'] = 'attachment; filename="pdfs.zip"'
                return response
Back to Top