0

When user click download button I want to generate multiple pdf Currently I can only generate one PDF

What I want is to generate two PDF from Django view when user click download button with weasyprint.

Below code only generate single PDF

def get(self, *args, **kwargs):
    obj = self.get_object()
    html_result = super(GenerateInvoicePDFView, self).get(*args, 
    **kwargs)
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="%s.pdf"' % 
    obj.name
    weasyprint.HTML(string= html_result.getvalue()).write_pdf(response)
    return response

This response should generate two PDF, is it possible ? Please help Thanks

Brown Bear
  • 19,655
  • 10
  • 58
  • 76
Akshay Sharma
  • 103
  • 1
  • 5
  • 1
    you can create archive or multi page pdf file, but no way for return multi file by response – Brown Bear Sep 02 '17 at 08:52
  • Possible duplicate of [Download multiple files with a single action](https://stackoverflow.com/questions/2339440/download-multiple-files-with-a-single-action) – Pythonist Sep 02 '17 at 09:36

1 Answers1

0

You cannot return multiple files in the response. Only solution I see is zipping them, sending them to user by email, or creating two separate download buttons.

How about:

view:

def get(self, *args, **kwargs):
    if 'file-1' in self.request.GET:
        obj = self.get_object(file='file-1')
    else:  # I assume you always want to download some file
        obj = self.get_object(file='file-2')

    html_result = super(GenerateInvoicePDFView, self).get(*args, 
    **kwargs)
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="%s.pdf"' % 
    obj.name
    weasyprint.HTML(string= html_result.getvalue()).write_pdf(response)
    return response

template:

<form action="" method="get">
    {{ form }}
    <input type="submit" name="file-1" value="Download file 1" />
    <input type="submit" name="file-2" value="Download file 2" />
</form>
Pythonist
  • 677
  • 5
  • 28
  • Ooh ! Can't I make them both download in single click – Akshay Sharma Sep 02 '17 at 09:20
  • So what approach would suit you best? Merging those 2 PDFs into one, zipping them or sending them by email? – Pythonist Sep 02 '17 at 09:21
  • HTTP does not support more than one file download at once. Apart from solutions I've listed in previous comment, you can bind JavaScript to your button, so on single click it will open 2 separate tabs and trigger 2 download action. Can't think of anything else at this moment. But zipping them is best solution, as it will work on every browser. – Pythonist Sep 02 '17 at 09:34
  • @Pythonist How would you go about that option of merging the PDFs into one or zipping them? – Abedy Aug 27 '19 at 11:36