Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

python - Django-wkhtmltopdf - call class to generate PDF, save to memory and add to zip

This is a multi-part question, I'm trying to accomplish two things:

  1. In a function, iterate through a query set and call my Generate PDF class

  2. Save the PDF in memory, append to a zip file.


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)

  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.

Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share