一、下載
1、python的imgkit、pdfkit庫
pip install imgkit
pip install pdfkit
2、wkhtmltopdf工具包
下載地址:https://wkhtmltopdf.org/downloads.html?
?
下載之后安裝,安裝完成會生成兩個程序,分別用來轉圖片和pdf:
二、使用
1、轉為圖片
import imgkitpath_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 pdfkitpath_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 imgkitoptions = {'encoding': 'utf8'}
imgkit.from_string(table, 'table.jpg',options=options)
?