((在Ubuntu服务器上使用'imgkit')wkhtmltopdf:无法连接到任何X显示器

问题描述 投票:0回答:1

我有一个在远程Ubuntu服务器上运行的python脚本。在代码的某个时刻,我创建了一个HTML文件,然后将其转换为png。因此,我选择使用imgkit,它可以很好地完成工作(在将python脚本上传到远程Ubuntu服务器之前,我在Mac OS上测试了我的代码):

import imgkit

imgkit.from_url('MyFile.html', 'MyFile.png')

现在,问题在于Ubuntu服务器没有安装imgkit和wkhtmltopdf。所以我运行了以下命令:

sudo pip install imgkit

然后:

sudo apt-get install wkhtmltopdf

然后返回错误:

QXcbConnection: Could not connect to display 
Could not connect to any X display.


You need to install xvfb(sudo apt-get install xvfb, yum install xorg-x11-server-Xvfb, etc), 
then add option: {"xvfb": ""}.

到目前为止很好。因此,我运行了以下命令:

sudo apt-get install xvfb

哪个工作。但是Ubuntu服务器仍然返回相同的错误。现在,有一件事,我不知道是什么:then add option: {"xvfb": ""}.甚至意味着。我试图在网上寻找答案,而人们之前都引用了该答案,但没有说明在终端中实际应该做什么或写什么。我也觉得我缺少wkhtmltopdf的扩展名,但是我不确定哪个(再次,我进行了在线搜索,但此时我比其他任何人都更加困惑。我在堆栈溢出时发现了类似的线程,但是没有什么比问题更严重的了)我正在经历)。任何帮助将不胜感激。

非常感谢最好的祝福,贝尔蒂

python ubuntu wkhtmltopdf xvfb imgkit
1个回答
0
投票

我没有找到解决问题的方法:then add option: {"xvfb": ""}

但是我能够使我的代码正常工作。有两种解决方案。

1)使用wkhtmltopdf:

import os

os.system("xvfb-run -a wkhtmltopdf %s %s"%('filenameIn.html','filenaneOut.png'))

这将产生PDF文件,而无需设置虚拟显示器。

2)使用pyvirtualdisplay设置虚拟显示:

from pyvirtualdisplay import Display

display = Display(visible=0, size=(600,600))
display.start()
imgkit.from_file("filenameIn.html", "filenameOut.html)
display.stop()

实际上,2)在回答之前,我在搜索StackOverflow时错过了它:"Could not connect to display" on EC2 Server

注:您可以结合使用1)和2):使用wkhtmltopdf直接转换为png,但要使用虚拟显示(否则png不会显示生成的图像,至少对我来说是这样)。

我认为这可能会有所帮助。 :)贝尔蒂

© www.soinside.com 2019 - 2024. All rights reserved.