pdfkit python自動化生成PDF

2022-08-26 15:30:14 字數 2701 閱讀 4842

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

度娘搜了下,很多部落格推薦python的第三方庫pdfkit,可以將網頁、html檔案以及字串生成pdf檔案。

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

使用pip安裝pdfkit

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

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

安裝wkhtmltopdf.exe檔案

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

務必要記住安裝位址,找到wkhtmltopdf.exe檔案所在的絕對路徑,後面要用到。

我這裡是預設路徑""c:\program files\wkhtmltopdf\bin\wkhtmltopdf.exe""

使用pdfkit庫生成pdf檔案

前面說過pdfkit可以將網頁、html檔案、字串生成pdf檔案。

# 導入庫

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'', 'out_1.pdf')

# 導入庫

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')

# 導入庫

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')

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

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

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

自動化測試 引言 自動化之我見

作為開篇,這裡先簡單介紹一下個人情況 本人非計算機專業的本科畢業,從事軟體測試工作一年多了,同樣的,接觸自動化測試領域也有一年了,打算開個部落格把我在工作中所學到與自動化測試有關的東西分享出來。好啦,下面開始說正題 自動化測試自身就是乙個很大的概念。逛過一些測試論壇的童鞋應該會知道qtp和loadr...

自動化測試 web自動化測試

自動化 由機器裝置代替人為完成制定目標的過程 優點 提高工作效率 減少勞動力 產品規格同一標準 批量生產 自動化測試 讓程式代替人為去驗證程式功能的過程,即在預設條件下執行程式系統 流程確定 搭建自動化框架 編寫測試用例,將其轉化為soupui 介面 自動化測試指令碼 執行自動化測試指令碼 輸出執行...

測試自動化 自動化測試的定義

相關術語 automated testing test tool,automated testing test suite,automated testing test script等.具體參見 http en.wikipedia.org wiki test automation 推薦書籍 1 軟體...