今天在学习python把网页生成pdf时,一直提示安装不上pdfkit,其实JetBrains PyCharm已经安装成功了,就是不加载这个包,后来想到本地用的Anaconda管理多版本python环境的,由于我本地JetBrains PyCharm项目中用的时py3.8,因此在Anaconda中切换至py3.8环境试一下:
(base) C:\Users\rakuchi>conda env list
# conda environments:
#
base * D:\software\Anaconda3
py3.8 D:\software\Anaconda3\envs\py3.8
py36 D:\software\Anaconda3\envs\py36
py37 D:\software\Anaconda3\envs\py37
(base) C:\Users\rakuchi>activate py3.8
(py3.8) C:\Users\rakuchi>pip install pdfkit
Collecting pdfkit
Using cached pdfkit-1.0.0-py3-none-any.whl (12 kB)
Installing collected packages: pdfkit
Successfully installed pdfkit-1.0.0
显示安装成功了,运行程序代码看下效果
# 导入库
import pdfkit
'''将网页生成pdf文件'''
def url_to_pdf(url, 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_url(url, to_file, configuration=config)
print('完成')
# 这里传入我知乎专栏文章url,转换为pdf
url_to_pdf(r'http://www.linqiong-ai.com/About.aspx?ClassID=43', 'out_2.pdf')
结果网页转换成功了
D:\software\Anaconda3\envs\py3.8\python.exe F:/work/pms/python/vippython/pdf/get_net_pdf.py
完成
Process finished with exit code 0
至此可以看到pdfkit包安装成功且程序可以运行了,记录一下,方便你我他。