django html to pdf using pdfkit and wkhtmltopdf

django html to pdf using pdfkit and wkhtmltopdf

In many ecommerce 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

  1. install python package "pdfkit" in virtualenv
    pip install pdfkit
  2. install system package "wkhtmltopdf" in ubuntu/debian
    sudo apt-get install wkhtmltopdf

django view and template forhtml to pdf

    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")
        return response
  2. invoice.html
        <style type="text/css">
          /* invoice styles here*/
          body{background: #efefef}
       <h1 style="color:red;">Hello World</h1>
  • 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/ and add the below code
    xvfb-run -a --server-args="-screen 0, 1024x768x24" /usr/bin/wkhtmltopdf_bin -q $*
  • After execute the below commands
    sudo chmod +x /opt/wkhtmltopdf_conf/
    sudo ln -s /opt/wkhtmltopdf_conf/  /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 :)




Support Me on Patreon