There are a few ways to export data to a PDF file using Django. All of them requires a third-party library so to
generate the file itself. First I will show how to return a PDF response, which can also be used if you are just
serving an existing PDF file. Then I will show how to use ReportLab and WeasyPrint.
Writing a PDF to Response
In the example below I’m using the Django’s FileSystemStorage class. It will also work if you simply use open()
instead. The FileSystemStorage sets the base_url to the project’s MEDIA_ROOT.
This way the user will be prompted with the browser’s open/save file. If you want to display the PDF in the browser
you can change the Content-Disposition to:
It relies on Pillow, which is a third-party Python Image Library. Sometimes it is a pain to get it installed.
If you are running into problems, please refer to the Pillow’s installation guide.
A “Hello, World” from Django docs:
Below an example of writing a PDF using SimpleDocTemplate and Paragraph:
ReportLab is a great library. It is very versatile. But there are a lot of configurations and settings to get the
printing right. So make sure you really want to go down that road.
Refer to the ReportLab Userguide for more references about the functions,
classes and all the available resources.
Downside: that huge list of dependency. If you were lucky enough to get it installed smoothly, move forward. If that’s
not the case, please refer to the official WeasyPrint installation guide.
A good thing about WeasyPrint is that you can convert a HTML document to a PDF. So you can create a regular Django
template, print and format all the contents and then pass it to the WeasyPrint library to do the job of creating