准备:
首先需要安装 pdfkit 库,使用 pip install pdfkit
命令就好了。
还需要安装 wkhtmltopdf 工具,本质就是利用这个工具来进行转换,pdfkit 库就是作为接口来调用该工具。
工具下载地址:
安装后的这个路径,在代码里配置下即可。
转换代码如下:
# -*- coding:utf-8 -*- import pdfkit def switch_pdf(html_path, pdf_path): ''' 作用:html文档转pdf文档 ''' # 指定wkhtmltopdf.exe程序的位置 wkthmltopdf_path = r'D:\server\wkhtmltopdf\bin\wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=wkthmltopdf_path) # 开始进行转换 pdfkit.from_file(html_path, pdf_path, configuration=config) print('转换完成!') # html文档的位置 html_path = "C:\\Users\\Administrator\\Desktop\\sonar使用文档.html" # 转换生成pdf文档的位置 pdf_path = "C:\\Users\\Administrator\\Desktop\\sonar使用文档.pdf" switch_pdf(html_path, pdf_path)
文件内容比较多的话,要多等一等,看到下面的效果就是转换完成了。
原文档如下:
转换后的效果图如下:
喜欢的点个赞❤吧!