Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wkhtmltopdf (pdfkit) Could not connect to any X display

I am trying to use wkhtmltopdf with Django ,nginx,uwsgi it works perfectly on development env running using manage.py runserver but when serving with nginx ans uwsgi i get this error:

wkhtmltopdf exited with non-zero code 1. error:
QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-isp'
qt.qpa.screen: QXcbConnection: Could not connect to display 
Could not connect to any X display.

Exception Location:     /home/isp/Env/isp/lib/python3.6/site-package/pdfkit/pdfkit.py in to_pdf, line 159

the command :

wkhtmltopdf http://www.google.com output.pdf

works perfectly on terminal and i used this guid to deploy the Django app https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-16-04#setting-up-the-uwsgi-application-server

i think it is related to virtualenv , i tried using this wrapper https://github.com/JazzCore/python-pdfkit/wiki/Using-wkhtmltopdf-without-X-server

but still having the same error

mycode :

import pdfkit
    pdfkit.from_file("./invoices/invoice"+str(booking_id)+"-"+str(invoice_id)+".html", "invoices/invoice_initial"+str(booking_id)+"-"+str(invoice_id)+".pdf")
like image 822
A.Mahamedi Avatar asked Aug 10 '18 13:08

A.Mahamedi


3 Answers

Solution

Instead of using

apt-get install wkhtmltopdf

I downloaded the latest version from the releases page and everything works now.

like image 68
A.Mahamedi Avatar answered Oct 23 '22 22:10

A.Mahamedi


Download the latest version from the official page

sudo wget -p ./ https://github.com/wkhtmltopdf/packaging/releases/download/0.12.6-1/wkhtmltox_0.12.6-1.bionic_amd64.deb

sudo apt install ./wkhtmltox_0.12.6-1.bionic_amd64.deb

It worked for me on Ubuntu 18.04

like image 9
Rahul Avatar answered Oct 23 '22 23:10

Rahul


You have 2 approaches to solve this problem.

  1. os.system("xvfb-run wkhtmltopdf %s %s"%(INPUT_URL, OUTPUT_FILE_PATH))

  2. Using pyvirtualdisplay:


    Installation:

    $ sudo apt-get install xvfb 
    $ sudo pip install pyvirtualdisplay
    

    Then:

    from pyvirtualdisplay import Display
    import pdfkit
    try:
       display.start()
       pdfkit.from_string(input_html_string, output_file_path)
       # pdfkit.from_url(input_url, output_file_path)
    finally:
       display.stop()
    
like image 8
Manoj Datt Avatar answered Oct 23 '22 22:10

Manoj Datt