有个需求,需要将HTML转换成图片。于是按照网上的办法找到imgkit库,windows操作很简单。

window:

pip install imgkit

python 代码如下:

 path_wk = r'D:\Program Files (x86)\software-install\wkhtmltopdf\bin\wkhtmltoimage.exe'
    config = imgkit.config(wkhtmltoimage=path_wk)
    options = {
        'crop-w': 1024,#需要截图的宽高位置,这里可以进行调整
        'crop-h': 645,
        'crop-x': 10,
        'crop-y': 150,
        'encoding': 'UTF-8',
    }
#转换HTML文件为图片
    html1 = imgkit.from_file(filename="./report/Automated_report_template_2022-06-09-14-26-07.html",  config=config, options=options, output_path="out1.jpg")
#转换HTML网址为图片
    html2 = imgkit.from_url(url="https://www.baidu.com",config=config,output_path="out2.png")

测试没有问题,完美输出。

部署到CentOS Linux release 7.9.2009 (Core)上

出现异常:centos 环境正确配置 wkhtmltopdf:cannot connect to X server

yum install wkhtmltopdf
yum -y install fontconfig libX11 libXext libXrender libjpeg openssl xorg-x11-fonts-75dpi xorg-x11-fonts-Type1 xorg-x11-server-Xvfb
# 解决中文乱码问题
yum groupinstall Fonts -y
mv /usr/bin/wkhtmltoimage /usr/bin/wkhtmltoimage_bin

vim /usr/bin/wkhtmltoimage.sh
#! /usr/bin/bash
xvfb-run -a --server-args="-screen 0, 1024x768x24" /usr/bin/wkhtmltoimage_bin $*

chmod a+x /usr/bin/wkhtmltoimage.sh
ln -s /usr/bin/wkhtmltoimage.sh /usr/bin/wkhtmltoimage

只要做好链接,就可以直接使用了

 

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐