生活随笔
收集整理的這篇文章主要介紹了
pdfkit生成pdf,可用于notebook
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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')
總結
以上是生活随笔為你收集整理的pdfkit生成pdf,可用于notebook的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。