我一直在尝试进行自定义 Django 管理操作,以允许我convert html page to pdf
然后download that pdf
,for each object separately if more than once is selected
. 由于只有一个请求要发送,我知道只有一个响应。所以我尝试将这些 pdf 文件放入 a 中zip file
,然后下载 zip 文件。但我最后看到的是corrupted zip file
. 不知道问题出在哪里
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