Published: Oct. 10, 2019 by lukemakin |  estimated reading time: 6 minutes
WeasyPrint is an elegant third-party solution for webdevelopers to create PDF files in a easy & convienient way. This library conists of a  rendering engine for HTML files and it's very easy to plug-in to given applications.

Weasy print can be applied as a function view, with a defiened queryset in order to retrieve objects from the database.It also requires the reference in the urls html template.

First thing first - let's install this package:

pip install WeasyPrint

Now let's head over to the and take a look at our view:

from django.http import HttpResponse
from django.template.loader import render_to_string
from weasyprint import HTML
import tempfile

def get_generated_problems_in_pdf(request):

# queryset
problems = Problem.objects.all()

# context passed in the template
context = {'problems': problems}

# render
html_string = render_to_string(
html = HTML(string=html_string)
result = html.write_pdf()

# http response
response = HttpResponse(content_type='application/pdf;')
response['Content-Disposition'] = 'inline; filename=problem_list.pdf'
response['Content-Transfer-Encoding'] = 'binary'
with tempfile.NamedTemporaryFile(delete=True) as output:
output = open(, 'rb')

return response

The next step is to define the urlpattern for our application:

urlpatterns = [
path('reports/generate/pdf/', get_generated_problems_in_pdf, name='pdf'),

And finally some extra code in our templates:

<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-
.tg .tg-ve35{border-color:#c0c0c0;text-align:left;vertical-align:middle}
.tg .tg-wo29{border-color:#c0c0c0;text-align:left;vertical-align:top}

{% for p in problems %}
<p>{{ p.timestamp }}</p>

<table class="tg" style="undefined;table-layout: fixed;">
<th>{{ p.category }}</th>
<th>{{ p.description }}</th>
<th>{{ p.problem_id }}</th>
<th>{{ p.breakdown }}</th>
{% endfor %}


This is it! Very simple solution i.e. to create the invoices in pdf. In the EXTRAS section we present how to add imgaes to our PDF files.

To view additional content login or create a free account
Share your thoughts

4 months, 2 weeks ago
this was helpful. thanks
Signup to the newsletter
To get the latest updates from pyplane
© copyright 2019