使用Weasyprint从Django视图生成多个PDF

时间:2020-12-14 00:28:05

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

当用户点击下载按钮我想生成多个pdf目前我只能生成一个PDF

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

我想要的是当用户点击带有weasyprint的下载按钮时,从Django视图生成两个PDF。

Below code only generate single PDF

下面的代码只生成单个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

这个响应应该生成两个PDF,是否可能?请帮忙谢谢

1 个解决方案

#1


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>

#1


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>