Python html 代码转成图片、PDF

一、下载

1、python的imgkit、pdfkit库

pip install imgkit
pip install pdfkit

2、wkhtmltopdf工具包

下载地址:https://wkhtmltopdf.org/downloads.html 

 

下载之后安装,安装完成会生成两个程序,分别用来转图片和pdf:

二、使用

1、转为图片

import imgkit

 
path_wkimg = r'C:\Program Files\wkhtmltopdf/bin\wkhtmltoimage.exe'  # 工具路径
cfg = imgkit.config(wkhtmltoimage=path_wkimg)

# 1、将html文件转为图片
imgkit.from_file(r'./helloworld.html', 'helloworld.jpg', config=cfg)

# 2、从url获取html,再转为图片
imgkit.from_url('https://httpbin.org/ip', 'ip.jpg', config=cfg)

# 3、将字符串转为图片
imgkit.from_string('Hello!','hello.jpg', config=cfg)

2、转为pdf

import pdfkit


path_wkpdf = r'C:\Program Files\wkhtmltopdf/bin\wkhtmltopdf.exe'  # 工具路径
cfg = pdfkit.configuration(wkhtmltopdf=path_wkpdf)
 
# 1、将html文件转为pdf
pdfkit.from_file(r'./helloworld.html', 'helloworld.pdf', configuration=cfg)
# 传入列表
pdfkit.from_file([r'./helloworld.html', r'./111.html', r'./222.html'], 'helloworld.pdf', configuration=cfg)
 
# 2、从url获取html,再转为pdf
pdfkit.from_url('https://httpbin.org/ip', 'ip.pdf', configuration=cfg)
# 传入列表
pdfkit.from_url(['https://httpbin.org/ip','https://httpbin.org/ip'], 'ip.pdf', configuration=cfg)
 
# 3、将字符串转为pdf
pdfkit.from_string('Hello!','hello.pdf', configuration=cfg)

3、乱码解决

import imgkit


options = {'encoding': 'utf8'}
imgkit.from_string(table, 'table.jpg',options=options)

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值