pdfkit | python自動化生成PDF


在用jupyter notebook寫代碼文檔的時候,有時需要導出pdf版本,但jupyter會報錯。我在想,除了網上的debug方法,還沒有其他方案可以生成pdf。

度娘搜了下,很多博客推薦Python的第三方庫pdfkit,可以將網頁、html文件以及字符串生成pdf文件。

其實也有很多軟件提供pdf生成服務,但這樣太不python了,那下面就來試試pdfkit怎么用吧!

三步實現自動生成pdf文檔:

  1. 使用pip安裝pdfkit

python版本 3.x,在命令行輸入:

pip install pdfkit

安裝pdfkit
安裝過程基本不會有啥問題,出現上面的Successfully installed pdfkit-0.6.1提示,說明安裝成功了。

  1. 安裝wkhtmltopdf.exe文件

注:pdfkit是基於wkhtmltopdf的python封裝,所以需要安裝wkhtmltopdf.exe。wkhtmltopdf是輕量級軟件,非常很容易安裝。

下載地址:
https://wkhtmltopdf.org/downloads.html

下載wkhtmltopdf

下載完成后,一路next,將wkhtmltopdf安裝好。

務必要記住安裝地址,找到wkhtmltopdf.exe文件所在的絕對路徑,后面要用到。

我這里是默認路徑""C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe""

安裝wkhtmltopdf

  1. 使用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'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')
  • html文件生成pdf【pdfkit.from_file()函數】
# 導入庫
import pdfkit

'''將html文件生成pdf文件'''
def html_to_pdf(html, 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_file(html, to_file, configuration=config)
    print('完成')

html_to_pdf('sample.html','out_2.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')
  1. 結論

本文講了如何在Python中使用pdfkit庫生成pdf文件,非常方便快捷,適合批量自動化操作。

我們看看生成的pdf效果如何:

pdf效果展示

整體頁面視覺不錯呦,趕快用起來吧!

獲取文中代碼和測試文件,在公眾號后台留言:pdfkit


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM