wkhtmltopdf (pdfkit) Could not connect to any X display
Asked Answered
Y

4

8

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")
Yorke answered 10/8, 2018 at 13:26 Comment(0)
Y
12

Solution

Instead of using

apt-get install wkhtmltopdf

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

Yorke answered 10/8, 2018 at 15:12 Comment(2)
After installing the latest version we also need to add option {"xvfb": ""}Began
Worked for me straight away. Thank you!Ampliate
O
9

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

Oshaughnessy answered 8/6, 2021 at 7:6 Comment(0)
S
8

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()
    
Superload answered 26/7, 2019 at 13:7 Comment(2)
I think one needs to instantiate the display?Gradin
you can simplify as: with Display(): pdfkit.from_string(input_html_string, output_file_path)Limon
L
0

I think it has something to do with X11 forwarding. You need to enable it on the server.

Check this out.

Loftin answered 10/8, 2018 at 13:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.