Generating and Returning PDF as response in Django

We might need to generate a receipt or a report in PDF format in Django app. In this article, we will see how to generate a dynamic PDF from html content and return it as a response.

Create a Django project. If you are not using virtual environment, we strongly recommend to do so.

Installing Dependencies:

Once virtual environment is ready and activated, install the below dependencies.

For pdfkit  to work, we need wkhtmltopdf  installed in our Linux system.

View code:

To generate the PDF, we first need to create the HTML template which will be converted to PDF.

If its a static PDF, then it is recommended to create it once and upload on the server and provide the direct downloading link.

However if its a dynamic PDF like payment receipt or weekly report, we need to pass the data to template. For this we will use get_template  method of template loader.

For the sake of simplicity, we will pass user’s name and date of birth to template. We convert the template to html string with variable values substituted in it and then generate the PDF from html string.

To return PDF as response, set the content_type  as application/pdf  in response.

views.py:

 

If you hit the URL, file will be downloaded.

generating pdf in django

 

Options:

pdfkit functions accept the configuration options in dictionary format.

 

We can generate PDF from a URL directly, from html or from text using function pdfkit.from_url , pdfkit.from_html  and pdfkit.from_text  respectively.

Source Code:

A sample minimal project is available on Github.

Read more about pdfkit here.

 

(Visited 703 times, 1 visits today)

You must read this :

2 thoughts on “Generating and Returning PDF as response in Django”

Leave a Reply

Your email address will not be published. Required fields are marked *