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 views.py 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(
'reports/problems.html',context)
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.write(result)
output.flush()
output = open(output.name, 'rb')
response.write(output.read())

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:


<html>
<head>
<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-
width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-
style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg .tg-ve35{border-color:#c0c0c0;text-align:left;vertical-align:middle}
.tg .tg-wo29{border-color:#c0c0c0;text-align:left;vertical-align:top}
</style>
</head>
<title>Test</title>

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

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

</body>
</html>

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.

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

johnny_j
1 month ago
this was helpful. thanks
Signup to the newsletter
To get the latest updates from pyplane
© copyright 2019 pyplane.com