1.安装pdfkit库
在命令行中输入如下命令
pip install pdfkit
出现上面的Successfully installed pdfkit-0.6.1提示,说明安装成功了
2.安装wkhtmltopdf.exe
文件
pdfkit是基于wkhtmltopdf的python封装,所以需要安装wkhtmltopdf.exe。wkhtmltopdf是轻量级软件,非常很容易安装
下载地址:
https://wkhtmltopdf.org/downloads.html
2.1 选择windows 64位
2.2下载完成后,一路next,将wkhtmltopdf
安装好。
务必要记住安装地址,找到wkhtmltopdf.exe
文件所在的绝对路径,后面要用到。我这里是默认路径""P:\Program Files\wkhtmltohdf\wkhtmltopdf\bin\wkhtmltopdf.exe"
"
3.使用pdfkit
库生成pdf文件
pdfkit可以将网页、html文件、字符串生成pdf文件
- 网页url生成pdf【pdfkit.from_url()函数】
# 导入库
import pdfkit
'''将网页url生成pdf文件'''
def url_to_pdf(url, to_file):
# 将wkhtmltopdf.exe程序绝对路径传入config对象
path_wkthmltopdf = r'P:\\Program Files\\wkhtmltohdf\\wkhtmltopdf\\bin\\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)
# 生成pdf文件,to_file为文件路径
pdfkit.from_url(url, to_file, configuration=config)
print('完成')
# 这里传入我jupyter的url,转换为pdf
url_to_pdf(r'http://localhost:8888/notebooks/%E4%BD%9C%E4%B8%9A/2022-3-18%20%E6%95%B0%E6%8D%AE%E6%8C%96%E6%8E%98.ipynb', '潘传志+2019212185+数据挖掘作业.pdf')
- html文件生成pdf【pdfkit.from_file()函数】
# 导入库
import pdfkit
'''将html文件生成pdf文件'''
def html_to_pdf(html, to_file):
# 将wkhtmltopdf.exe程序绝对路径传入config对象
path_wkthmltopdf = r'P:\\Program Files\\wkhtmltohdf\\wkhtmltopdf\\bin\\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)
# 生成pdf文件,to_file为文件路径
pdfkit.from_file(html,to_file , configuration=config)
print('完成')
html_to_pdf('2022-3-18 数据挖掘.html','潘传志+2019212185+数据挖掘作业.pdf')
- 字符串生成pdf【pdfkit.from_string()函数】
# 导入库
import pdfkit
'''将字符串生成pdf文件'''
def str_to_pdf(string, to_file):
# 将wkhtmltopdf.exe程序绝对路径传入config对象
path_wkthmltopdf = r'C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)
# 生成pdf文件,to_file为文件路径
pdfkit.from_string(string, to_file, configuration=config)
print('完成')
str_to_pdf('This is test!','out_3.pdf')