python生成pdf文件,使用pdfkit很方便。由于pdfkit要依赖系统中的wkhtmltopdf,所以要先安装wkhtmltopdf。
1.在网站https://wkhtmltopdf.org/downloads.html上下载自己需要的版本,当然也可以使用命令在线安装。
# mac环境下homebrew安装,类似于linux的apt-get和yum
brew cask install wkhtmltopdf

2.安装pdfkit包
pip install pdfkit
3.可以直接使用pdfkit了
# url页面转化为pdf
pdfkit.from_url(url, file_path)
# 文本内容转化为pdf
pdfkit.from_string(text, file_path)
# 文件转化为pdf
pdfkit.from_file(file, file_path)
# 也可以是打开的文件
with open('file.html') as f:
pdfkit.from_file(f, 'out.pdf')
网友评论