问题
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")
回答1:
Solution
Instead of using
apt-get install wkhtmltopdf
I downloaded the latest version from the releases page and everything works now.
回答2:
You have 2 approaches to solve this problem.
os.system("xvfb-run wkhtmltopdf %s %s"%(INPUT_URL, OUTPUT_FILE_PATH))
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()
回答3:
I think it has something to do with X11 forwarding. You need to enable it on the server.
Check this out.
来源:https://stackoverflow.com/questions/51787618/wkhtmltopdf-pdfkit-could-not-connect-to-any-x-display