python html生成图片_pythonhtml2image: imgkit 和 wkhtmltoimage的坑

场景

需要根据信息,将一个动态页面生成图片。

经过调研,发现只有imgkit符合要求。

imgkit其实是调用wkhtmltopdf的wkhtmltoimage(wkhtmltopdf包含wkhtmltopdf和wkhtmltoimage两个工具)来实现功能。

wkhtmltopdf和wkhtmltoimage是通过调用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上无法展示图片导致(但是哪里设置需要去展示了呢,我根本没打开生成的图片)。所以通过设置环境变量来规避。

os.environ['QT_QPA_PLATFORM']='offscreen'

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

中文/Font

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

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

最后来看,应该就是缺少字体文件导致。

具体来讲,在我的Mac上的/Library/Fonts/Microsoft路径下,找到SimSun.ttf文件。

然后将文件拷贝到Ubuntu下的/usr/share/fonts。

同时,在html文本的

标签下添加字体设置。

* {

padding: 0;

margin: 0;

font-family: SimSun;

}

就好了。

感想……

wkhtmltopdf的文档真是。。。▄█▀█●

像解谜一样。。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值