How can I convert a HTML Page to PDF using Django

前端 未结 1 1759
太阳男子
太阳男子 2021-02-01 10:40

I have a web app in Django. It\'s a plataform to store bills and invoices. Now i\'m trying to export those bills un PDF.

I\'m using xhtml2pdf but it\'s not working.

1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-01 11:24

    Try using this code. It works for me. Change "template_testing.html" for your template and add your data to render on "data = {}"

    views.py:

    import os
    from django.conf import settings
    from django.http import HttpResponse
    from django.template import Context
    from django.template.loader import get_template
    import datetime
    from xhtml2pdf import pisa 
    
    
    def generate_PDF(request):
        data = {}
    
        template = get_template('template_testing.html')
        html  = template.render(Context(data))
    
        file = open('test.pdf', "w+b")
        pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file,
                encoding='utf-8')
    
        file.seek(0)
        pdf = file.read()
        file.close()            
        return HttpResponse(pdf, 'application/pdf')
    

    0 讨论(0)
提交回复
热议问题