Eld*_*mir 8 python pdf django html-to-pdf
从python2中的django网页生成pdf有很多种不同的方法.最干净的可能是比萨和报告.但这些对python3不起作用.
到目前为止,我唯一成功的方法是渲染模板,将其写入文件,然后通过subprocess.popen使用wkhtmltopdf.这可以正常工作,但它不会加载任何我的静态文件,如CSS和图像.
有没有合适的解决方案?可以wkhtmltopdf从命令行读取我的静态文件,在某种程度上,还是像pisa/reportlab这样的库,它支持python3?
我无法找到这样的图书馆
Chr*_*itt 11
你可以使用Weasyprint.您可以轻松直接渲染.
你可以这样做:
html = HTML(string=htmlstring)
main_doc = html.render()
pdf = main_doc.write_pdf()
return HttpResponse(pdf, content_type='application/pdf')
Run Code Online (Sandbox Code Playgroud)
要将Django视图呈现为HTML,您只需使用快捷方式即可 render_to_string(self.template_name, context, context_instance=RequestContext(self.request))
请注意,将此与同步Web服务器/ WSGI服务器一起使用时,将阻止所有请求,直到呈现PDF.所以考虑使用ASYNC Worker.
我研究了 Weasyprint、wkhtmltopdf 甚至 LaTeX,但它们都具有外部二进制依赖项,很难部署到 Heroku 等服务。
到目前为止,我发现在 Python 3 上的 Django 中工作的最佳组合是使用 Reportlab (现在可以在 Python 3 上工作)+ xhtml2pdf。xhtml2pdf 最近才添加了 beta Python 3 支持,因此您需要使用以下命令安装它:
pip install --pre xhtml2pdf
Run Code Online (Sandbox Code Playgroud)
如果安装了这两个,则可以直接使用 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
Run Code Online (Sandbox Code Playgroud)
在urls.py中添加如下内容:
url(r'invoice/(?P<pk>[^/]+)/$', InvoicePDFView.as_view(), name='invoice')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5832 次 |
最近记录: |