python包pdfkit(wkhtmltopdf)?將HTML轉換為PDF的操作方法
python包-pdfkit 將HTML轉換為PDF
什么是pdfkit
pdfkit,把HTML+CSS格式的文件轉換成PDF格式文檔的一種工具。它就是html轉成pdf工具包wkhtmltopdf的Python封裝。所以,必須手動安裝wkhtmltopdf。
安裝
首先需要安裝 pdfkit 庫,使用 pip install pdfkit 命令就好了。
還需要安裝 wkhtmltopdf 工具,本質就是利用這個工具來進行轉換,pdfkit 庫就是作為接口來調用該工具。
python版本 3.x,在命令行輸入:
$sudo apt-get install wkhtmltopdf
工具下載地址:
wkhtmltopdf 官網:https://wkhtmltopdf.org/downloads.html
Ubuntu系統(tǒng)可以直接使用以下命令安裝:
$sudo yum intsall wkhtmltopdf
CentOS系統(tǒng)可以直接使用以下命令安裝:
$sudo yum intsall wkhtmltopdf
使用
將url生成pdf文件
不指定wkhtmltopdf,會從系統(tǒng)的默認執(zhí)行路徑下找 wkhtmltopdf
import pdfkit '''將url生成pdf文件''' def url_to_pdf(url, to_file): pdfkit.from_url(url, to_file,verbose=True) url_to_pdf('http://www.baidu.com','out_3.pdf')
指定 wkhtmltopdf 的位置:
import pdfkit '''將url生成pdf文件''' def url_to_pdf(url, to_file): config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/wkhtmltopdf') pdfkit.from_url(url, to_file,configuration=config,verbose=True) url_to_pdf('http://www.baidu.com','out_3.pdf')
字符串生成pdf【pdfkit.from_string()函數(shù)】
# 導入庫 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')
報錯
報錯OSError: No wkhtmltopdf executable found
在使用pdfkit.from_string或者pdfkit.from_file或者pdfkit.from_url將字符串、文件或者網頁內容轉化為pdf時,報錯:
OSError: No wkhtmltopdf executable found
原因很明顯,就是沒找到可執(zhí)行的wkhtmltopdf文件,也就是未找到wkhtmltopdf.exe文件。
python的pdfkit擴展包使用時需要基于wkhtmltopdf.exe這個可執(zhí)行文件才可運行,因此需要先安裝wkhtmltopdf。
對于windows系統(tǒng),可以在(https://wkhtmltopdf.org/downloads.html)下載安裝,然后將該程序的執(zhí)行文件路徑添加到環(huán)境變量中(這樣即可直接用pdfkit擴展包,否則需要在使用pdfkit時,指明該程序的路徑)
Ubuntu系統(tǒng)可以直接使用以下命令安裝:
$sudo apt-get install wkhtmltopdf
CentOS系統(tǒng)可以直接使用以下命令安裝:
$sudo yum intsall wkhtmltopdf
到此這篇關于python包pdfkit(wkhtmltopdf) 將HTML轉換為PDF的文章就介紹到這了,更多相關python pdfkit將HTML轉換為PDF內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Django 多表關聯(lián) 存儲 使用方法詳解 ManyToManyField save
今天小編就為大家分享一篇Django 多表關聯(lián) 存儲 使用方法詳解 ManyToManyField save,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08使用python tkinter開發(fā)一個爬取B站直播彈幕工具的實現(xiàn)代碼
這篇文章主要介紹了使用python tkinter開發(fā)一個爬取B站直播彈幕的工具,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02Python + selenium + requests實現(xiàn)12306全自動搶票及驗證碼破解加自動點擊功能
這篇文章主要介紹了Python + selenium + requests實現(xiàn)12306全自動搶票及驗證碼破解加自動點擊功能,需要的朋友可以參考下2018-11-11