wkhtmltopdf (pdfkit) 无法连接到任何 X 显示器

wkhtmltopdf (pdfkit) Could not connect to any X display

我正在尝试将 wkhtmltopdf 与 Django、nginx、uwsgi 一起使用 它在开发环境 运行 上使用 manage.py runserver 完美运行 但是当使用 nginx ans uwsgi 服务时我得到这个错误:

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

命令:

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

在终端上完美运行 我用这个 guid 来部署 Django 应用程序 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

我认为它与 virtualenv 有关,我尝试使用这个包装器 https://github.com/JazzCore/python-pdfkit/wiki/Using-wkhtmltopdf-without-X-server

但还是出现同样的错误

我的代码:

import pdfkit
    pdfkit.from_file("./invoices/invoice"+str(booking_id)+"-"+str(invoice_id)+".html", "invoices/invoice_initial"+str(booking_id)+"-"+str(invoice_id)+".pdf")

我觉得跟X11转发有关系。您需要在服务器上启用它。

检查 this

解决方案

而不是使用

apt-get install wkhtmltopdf

我从 releases page 下载了最新版本,现在一切正常。

你有 2 种方法来解决这个问题。

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

  2. 使用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()
    

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

它在 Ubuntu 18.04

对我有用