我研究了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')