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")
Instead of using
apt-get install wkhtmltopdf
I downloaded the latest version from the releases page and everything works now.
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
You have 2 approaches to solve this problem.
os.system("xvfb-run wkhtmltopdf %s %s"%(INPUT_URL, OUTPUT_FILE_PATH))
Using pyvirtualdisplay
:
$ sudo apt-get install xvfb
$ sudo pip install pyvirtualdisplay
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With