python imgkit将HTML转化为图片

有个需求,需要将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

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

 

 

  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值