【问题标题】:Generate multiple PDF from Django view with Weasyprint使用 Wea​​syprint 从 Django 视图生成多个 PDF
【发布时间】:2018-02-11 05:10:42
【问题描述】:

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

当用户使用 weasyprint 单击下载按钮时,我想要从 Django 视图生成两个 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

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

【问题讨论】:

标签: python django pdf weasyprint


【解决方案1】:

您不能在响应中返回多个文件。我看到的唯一解决方案是压缩它们,通过电子邮件将它们发送给用户,或者创建两个单独的下载按钮。

怎么样:

查看:

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

模板:

<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>

【讨论】:

  • 哦!我不能让它们都通过单击下载吗
  • 那么哪种方法最适合您?将这 2 个 PDF 合并为一个、压缩它们还是通过电子邮件发送?
  • HTTP 不支持一次下载多个文件。除了我在之前的评论中列出的解决方案之外,您还可以将 JavaScript 绑定到您的按钮,因此单击它会打开 2 个单独的选项卡并触发 2 个下载操作。此刻想不出别的。但是压缩它们是最好的解决方案,因为它适用于所有浏览器。
  • @Pythonist 您将如何选择将 PDF 合并为一个或压缩它们?
猜你喜欢
  • 2020-01-30
  • 2018-08-05
  • 1970-01-01
  • 2021-09-23
  • 2021-10-20
  • 2019-06-06
  • 2016-09-26
  • 2016-11-04
  • 1970-01-01
相关资源
最近更新 更多