Django Html To Pdf Using Pdfkit And Wkhtmltopdf¶
In many e-commerce django/python projects we sent invoices to the users in an email. We generally attach pdf documents to the email while sending the invoices to the user. Most of these invoices are pdf documents. Django is the most used python web framework of python programming language. In django, to generate invoice we generally uses html templates and renders them using the context to get the html. To generate the invoice from the html we use a python package"pdfkit"and the system package "wkhtmltopdf".
install required packages for django html to pdf¶
- install python package
pdfkit
invirtualenv
pip install pdfkit
- install system package "wkhtmltopdf" in ubuntu/debian
sudo apt-get install wkhtmltopdf
django view and template forhtml to pdf¶
views.py
import pdfkit
from django.http import HttpResponse
from django.template import loader
def create_pdf(request):
html = loader.render_to_string('invoice.html', {})
output= pdfkit.from_string(html, output_path=False)
response = HttpResponse(content_type="application/pdf")
response.write(output)
return response
invoice.html
<html>
<head>
<style type="text/css">
/* invoice styles here*/
body{background: #efefef}
</style>
</head>
<body>
<h1 style="color:red;">Hello World</h1>
</body>
</html>
Note: In the email template it's highly recommended to use inline styles.
Usage of wkhtmltopdf in ubuntu server¶
- wkhtmltopdf is works with the help of X graphic server.
- If we want to use it in the server then it will become a problem that means it will not works.
- To make it work in the server we need to install a X server (xvfb).
sudo apt-get install xvfb
- After installing the "xvfb" we need to use it along with the "wkhtmltopdf". To do that execute the below commands in the terminal.
echo which wkhtmltopdf
# /usr/bin/wkhtmltopdf
sudo mv /usr/bin/wkhtmltopdf /usr/bin/wkhtmltopdf_bin
- Now, create a fine in /opt/wkhtmltopdf_conf/wkhtmltopdf.sh and add the below code
#!/bin/bash
xvfb-run -a --server-args="-screen 0, 1024x768x24" /usr/bin/wkhtmltopdf_bin -q $*
- After execute the below commands
`sh sudo chmod +x /opt/wkhtmltopdf_conf/wkhtmltopdf.sh sudo ln -s /opt/wkhtmltopdf_conf/wkhtmltopdf.sh /usr/bin/wkhtmltopdf
Now, test
it on the server. It will work.
If you get any errors please let me know I\'m happy to help you :)
References