我研究了Weasyprint、wkhtmltopf甚至LaTeX,但它们都有外部二进制依赖项,很难部署到Heroku等服务中。
到目前为止,我在Django中找到的对Python 3有效的最佳组合是使用Reportlab(现在对python3有效)+xhtml2pdf。xhtml2pdf最近才添加了beta Python 3支持,因此您需要使用以下工具安装它:pip install --pre xhtml2pdf
如果安装了这两个模板,则可以直接使用xhtml2pdf,也可以安装django-easy-pdf包,该包提供要继承的模板视图和示例基本模板样式,以便快速入门。按照他们的快速启动说明,您可以快速准备一些内容,例如呈现为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[^/]+)/$', InvoicePDFView.as_view(), name='invoice')