This is a multi-part question, I'm trying to accomplish two things:
In a function, iterate through a query set and call my Generate PDF class
Save the PDF in memory, append to a zip file.
views.py
import ZipFile
import io
...
def zip_pdf(request, foo_id):
""" Collect a record and iterate through a queryset of related records, generating PDFs and saving them into a zip file"""
foo = Foo.objects.get(id=foo_id)
bars = Bar.objects.filter(foo=foo)
waldos = Waldo.objects.filter(foo=foo)
# Prepare the zip file
zipfilename = f"{foo.name} package"
buffer = io.BytesIO()
zipf = zipfile.ZipFile(buffer, 'w', zipfile.ZIP_DEFLATED)
# Add files in the database to the zip
for bar in bars:
filename = str(bar)
filepath = bar.file.path
zipf.write(filepath, f"bars/{filename}")
# Generate PDF files and add to zip
for waldo in waldos:
# Call the class based view to generate PDF
# *** This part is wrong, I am not sure how do it correctly ***
# *** Currently it will present me with the option to save or open the first generated PDF and stops ***
return Generate_PDF.as_view()(request, waldo_id=waldo.id)
zipf.close()
response = HttpResponse(buffer.getvalue())
content = f"attachment; filename={zipfilename}"
response['Content-Disposition'] = content
return response
...
Class Generate_PDF(PDFTemplateView):
template_name = 'appname/generatepdf.html'
cmd_options = [
'page-size': 'Letter',
'viewport-size': '1920x1080',
'footer-left': '[page]/[tppage]',
'no-outline': True
]
def get_filename(self):
filename = f"PDF Record for {self.waldo}.pdf"
return filename
def get_context_data(self, **kwargs):
self.waldo = Waldo.objects.get(id=self.kwargs['waldo_id']
context = {'waldo': self.waldo}
return context
So my PDF generation works great, and zipping files works great. I'm just not sure how to call my class based view and save the PDF to memory so I can add it to the zip file.
I've tried searching but I feel that I am missing something that is connecting the dots.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…