Search code examples
django-templatespdfkit

How to get the rendered template from django?-pdfkit


I have a template in my django application and I need to get it rendered in a variable or save it in an html file.

My goal is to convert the html rendering of the template to pdf, I am using pdfkit since it is the best html to pdf converter I have seen, reportlab does not do what I want.

When I try to do something like this:

pdf = pdfkit.from_file ('app / templates / app / table.html', 'table.pdf')

I get the pdf but print something like this:

enter image description here

I appreciate any help!


Solution

  • This is the solution to my case that I use django 2.0.1 and pdfkit 0.6.1:

    To obtain the template:

    template = get_template ('plapp / person_list.html')
    

    To render it with the data:

    html = template.render ({'persons': persons})
    

    To continuation the definition of the method in views.py, the one that downloads the pdf directly in the browser:

    def pdf(request):
        persons = Person.objects.all()
        template = get_template('plapp/person_list.html')
        html = template.render({'persons': persons})
        options = {
            'page-size': 'Letter',
            'encoding': "UTF-8",
        }
        pdf = pdfkit.from_string(html, False, options)
        response = HttpResponse(pdf, content_type='application/pdf')
        response['Content-Disposition'] = 'attachment;
        filename="pperson_list_pdf.pdf"'
        return response