pythonhtml2image: imgkit 和 wkhtmltoimage的坑

场景

需要根据信息,将一个动态页面生成图片。
经过调研,发现只有imgkit符合要求。
imgkit其实是调用wkhtmltopdf的wkhtmltoimagewkhtmltopdf包含wkhtmltopdfwkhtmltoimage两个工具)来实现功能。
wkhtmltopdfwkhtmltoimage是通过调用QT来实现功能:

wkhtmltopdf and wkhtmltoimage are command line tools to render HTML into PDF and various image formats using the QT Webkit rendering engine.

$PATH

imgkit中,通过

self.wkhtmltoimage = subprocess.Popen(['which', 'wkhtmltoimage'], stdout=subprocess.PIPE).communicate()[0].strip()

来获取wkhtmltoimage工具。

我在shell下,以及IPython中都可以正确获得结果,但是在PyCharm中一直返回空字符串。解决办法是设置系统变量$PATH。或者使用imgkit文档中的方法:

config = imgkit.config(wkhtmltoimage='/opt/bin/wkhtmltoimage')
imgkit.from_string(html_string, output_file, config=config)

就是把wkhtmltoimage的路径传入即可。

安装:Mac OSX VS Linux Ubuntu

wkhtmltoimage的Github页面写的安装方法都不能用!
Mac OSX操作系统下,不能使用brew install wkhtmltopdf安装,必须下二进制包。
Ubuntu操作系统下,很悲剧,通过sudo apt-get install wkhtmltopdf安装的包是阉割版。
我跑程序的时候Mac可以用,但是一到服务器上就报错,找了半天,居然就在上面这条命令下方,文档中写道:

Warning! Version in debian/ubuntu repos have reduced functionality (because it compiled without the wkhtmltopdf QT patches), such as adding outlines, headers, footers, TOC etc. To use this options you should install static binary from wkhtmltopdf site or you can use this script.

注意这句:because it compiled without the wkhtmltopdf QT patches
没有QT就报错。
Ubuntu上的安装其实还是得去下二进制包了。

长宽

在html页面中写是没用的。必须使用imgkit中的option来设置。

    options = {
        'width': width,
        'height': height,
        'encoding': 'UTF-8',
    }
    data = imgkit.from_string(html, False, config=config, options=options)

这个问题简单,文档中写得很清楚。

无法展示

Ubuntu上报错:QXcbConnection: Could not connect to display
通过搜索,找到以下信息:
https://github.com/ContinuumIO/anaconda-issues/issues/1806
https://github.com/ipython/ipython/issues/10627

是因为Ubuntu上无法展示图片导致(但是哪里设置需要去展示了呢,我根本没打开生成的图片)。所以通过设置环境变量来规避。

os.environ['QT_QPA_PLATFORM']='offscreen'
os.environ['DISPLAY']=':0.0'

中文/Font

万事具备,但是Mac上中文就是能够正确展示,Ubuntu上就是框框(连乱码都没有)。

后来通过搜索,找到以下信息:
http://www.cnblogs.com/liangml/p/6421573.html
linux 安装 wkhtmltopdf 中文乱码或者空白解决方法
https://stackoverflow.com/questions/11859872/wkhtmltopdf-encoding-issue
https://stackoverflow.com/questions/11446894/unicode-chars-are-converted-to-broken-symbols-when-i-use-wkhtmltopdf
https://blog.yctin.com/install-wkhtmltopdf-wkhtmltoimage-to-centos-with-chinese-asian-fonts-support/
https://github.com/wkhtmltopdf/wkhtmltopdf/issues/2128

按图索骥,我先尝试了很多办法,比如更改html文本的font-family,更改options的值encoding: 'gbk',都没起效。

最后来看,应该就是缺少字体文件导致。
具体来讲,在我的Mac上的/Library/Fonts/Microsoft路径下,找到SimSun.ttf文件。
然后将文件拷贝到Ubuntu下的/usr/share/fonts
同时,在html文本的标签下添加字体设置。

    

就好了。

感想……

wkhtmltopdf的文档真是。。。▄█▀█●
像解谜一样。。。。

你可能感兴趣的:(python)