【问题标题】:Python3 Django -> HTML to PDFPython3 Django -> HTML 到 PDF
【发布时间】:2015-01-15 19:09:45
【问题描述】:

在 python2 中有很多不同的方法可以从 django 网页生成 pdf。最干净的,可能是比萨和reportlab。 但这些不适用于 python3。

到目前为止,我唯一成功的方法是渲染模板,将其写入文件,然后通过 subprocess.popen 使用 wkhtmltopdf。这工作正常,但它不会加载我的任何静态文件,例如 css 和图像。

有没有合适的解决方案? wkhtmltopdf 可以从命令行以某种方式读取我的静态文件,还是有像 pisa/reportlab 这样支持 python3 的库?

我一直没能找到这样的图书馆

【问题讨论】:

    标签: python django pdf html-to-pdf


    【解决方案1】:

    您可以使用Weasyprint。您可以轻松地直接渲染。

    你可以这样做:

        html = HTML(string=htmlstring)
        main_doc = html.render()
        pdf = main_doc.write_pdf()
        return HttpResponse(pdf, content_type='application/pdf')
    

    要将您的 Django 视图呈现为 HTML,您可以简单地使用快捷方式 render_to_string(self.template_name, context, context_instance=RequestContext(self.request))

    请注意,当将 This 与同步 Web 服务器/WSGI 服务器一起使用时,所有请求都将被阻止,直到呈现 PDF。所以考虑使用 ASYNC Worker。

    【讨论】:

    • 谢谢你!它没有出现在我的任何搜索中,但效果很好。安装它需要一些努力,因为它需要一些非 python 库,但我管理了。非常感谢
    • 我尝试使用 Wea​​syprint,它适用于 Python3,但它消耗大量内存 - 从不到 1M 的 html 生成 PDF 需要 500M。
    【解决方案2】:

    wkhtmltopdf 需要

    • 要内联的 CSS
    • 静态文件本地存在于服务器上
    • 静态文件地址为操作系统路径,例如:/home/ubuntu/project/project/static/file_name

    【讨论】:

      【解决方案3】:

      我研究了 Weasyprint、wkhtmltopdf 甚至 LaTeX,但它们都具有难以部署到 Heroku 等服务的外部二进制依赖项。

      到目前为止,我发现在 Python 3 上的 Django 中工作的最佳组合是使用 Reportlab(现在在 Python 3 上工作)+xhtml2pdf。 xhtml2pdf 最近才添加了 beta Python 3 支持,因此您需要安装它:

      pip install --pre xhtml2pdf
      

      如果您安装了这两个,您可以直接使用 xhtml2pdf 或安装 django-easy-pdf 包,该包提供了一个可供继承的 TemplateView 以及一个示例基本模板和样式,以帮助您快速入门。按照他们的快速入门说明,您可以快速准备诸如呈现为 PDF 的详细视图之类的内容,例如:

      class InvoicePDFView(PDFTemplateView):
          template_name = "invoice_pdf.html"
      
          def get_context_data(self, **kwargs):
              context = super().get_context_data(**kwargs)
              myinstance = get_object_or_404(MyModel, pk=context['pk'])
              context['myinstance'] = myinstance
              return context
      

      在你的 urls.py 中你会添加类似的东西:

      url(r'invoice/(?P<pk>[^/]+)/$', InvoicePDFView.as_view(), name='invoice')
      

      【讨论】:

        【解决方案4】:

        我在 Python3 中尝试过 pydf,它工作正常。

        pip install python-pdf
        

        对于python2,请使用pip install python-pdf==0.30.0

        文档https://github.com/tutorcruncher/pydf

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-12-18
          • 1970-01-01
          • 2011-11-22
          • 1970-01-01
          • 2014-10-01
          • 2020-04-12
          • 1970-01-01
          • 2011-02-18
          相关资源
          最近更新 更多