imgkit分辨率_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上報錯: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的文檔真是。。。▄█?█●
像解謎一樣。。。。
總結
以上是生活随笔為你收集整理的imgkit分辨率_pythonhtml2image: imgkit 和 wkhtmltoimage的坑的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html代码大全(很全的)_HTML教学
- 下一篇: python解压到指定文件夹_在Pyth