In this blog, we will learn how to create PDFs using wkhtmltopdf in Django.
Requirements
You need wkhtmltopdf available in your system and accesible in the command prompt.
Windows: you can download an installer for each architecture (x86 and x64) in the installation area. Although you can change the path of the wkhtmltopdf executable later in the code, is recommendable to have wkhtmltopdf accesible as an environment variable on your system.
Debian/Ubuntu: You can install the distribution from wkhtmltopdf directly in the console using the following command :
$ sudo apt-get install wkhtmltopdf |
Implementation
PDFKit is a python wrapper to convert html to pdf using the webkit rendering engine (wkhtmltopdf) and qt.
Include the PDFKit library into your django project using the following command :
$ pip install pdfkit |
The use of PDFKit is really simple and cover almost all the use cases :
- Create a PDF from a html string.
- Create a PDF from a web url (external or project url).
#import pdfkit into your class import pdfkit # Generate PDF from a web URL (maybe only from your project) pdfkit.from_url('http://google.com', 'document.pdf') # Generate PDF from a html file. pdfkit.from_file('file.html', 'document.pdf') # Generate PDF from a plain html string. pdfkit.from_string('Hello!', 'document.pdf') # Save the PDF in a variable myPdf = pdfkit.from_url('http://google.com', False) |
And we are basically generating PDFs easily and quick.
Examples
Following examples shows easy way to generate PDFs with Django and PDFKit
Save PDF on the server
import pdfkit from django.http import HttpResponse def index(request): pdf = pdfkit.from_url("http://www.gktcs.in", "gktcs.pdf") return HttpResponse("Everything working good, check out the root of your project to see the generated PDF.") |
The above example will create a PDF in the root of your Django project.
Return PDF as response
We can retrieve directly a file from PDFKit and saving it in your system, just provide False as the destination parameter.
We can use the following code to return a PDF as response :
import pdfkit from django.http import HttpResponse def index(request): # Use False instead of output path to save pdf to a variable pdf = pdfkit.from_url('http://www.gktcs.in', False) response = HttpResponse(pdf,content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="gktcs.pdf"' return response |
PDF Settings
You can specify all wkhtmltopdf options. You can drop ‘–’ in option name. If option without value, use None, False or '' for dict value:
options = { 'page-size': 'Letter', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', 'encoding': "UTF-8", 'no-outline': None } pdfkit.from_url('http://google.com', 'out.pdf', options=options) |