Python3 Django -> HTML to PDF

前端 未结 4 574
陌清茗
陌清茗 2020-12-15 00:28

There are a lot of different ways of generating pdfs from a django webpage in python2. The most clean, probably, is pisa and reportlab. These do not work for python3 though.

4条回答
  •  独厮守ぢ
    2020-12-15 00:57

    I looked into Weasyprint, wkhtmltopdf and even LaTeX, but all have external binary dependencies that are difficult to deploy to services such as Heroku.

    The best combination I found so far that works in Django on Python 3 is using Reportlab (now works on Python 3) + xhtml2pdf. xhtml2pdf only recently added beta Python 3 support so you need to install it with:

    pip install --pre xhtml2pdf
    

    If you have these two installed, you can either use xhtml2pdf directly or install the django-easy-pdf package which provides a TemplateView to inherit from and an example base template & styling to get you started quickly. Follow their quickstart instructions and you can quickly prepare something like a detail view that renders to PDF like:

    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
    

    And in your urls.py you'd add something like:

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

提交回复
热议问题