參考地址 https://www.jianshu.com/p/489c3aff61bd/
1 安裝
pip install pdfkit
2 安裝
Wkhtmltopdf 可百度
3
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'https://zhuanlan.zhihu.com/p/69869004', 'out_1.pdf')
# 導入庫
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')
