欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python包pdfkit(wkhtmltopdf)?將HTML轉(zhuǎn)換為PDF的操作方法

 更新時間:2022年04月21日 11:08:00   作者:西京刀客  
pdfkit,把HTML+CSS格式的文件轉(zhuǎn)換成PDF格式文檔的一種工具。它就是html轉(zhuǎn)成pdf工具包wkhtmltopdf的Python封裝。所以,必須手動安裝wkhtmltopdf,這篇文章主要介紹了python包pdfkit(wkhtmltopdf)將HTML轉(zhuǎn)換為PDF,需要的朋友可以參考下

python包-pdfkit 將HTML轉(zhuǎn)換為PDF

什么是pdfkit

pdfkit,把HTML+CSS格式的文件轉(zhuǎn)換成PDF格式文檔的一種工具。它就是html轉(zhuǎn)成pdf工具包wkhtmltopdf的Python封裝。所以,必須手動安裝wkhtmltopdf。

安裝

首先需要安裝 pdfkit 庫,使用 pip install pdfkit 命令就好了。
還需要安裝 wkhtmltopdf 工具,本質(zhì)就是利用這個工具來進行轉(zhuǎn)換,pdfkit 庫就是作為接口來調(diào)用該工具。
python版本 3.x,在命令行輸入:

$sudo apt-get install wkhtmltopdf

工具下載地址:
wkhtmltopdf 官網(wǎng):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ù)】

# 導(dǎo)入庫
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將字符串、文件或者網(wǎng)頁內(nèi)容轉(zhuǎn)化為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

到此這篇關(guān)于python包pdfkit(wkhtmltopdf) 將HTML轉(zhuǎn)換為PDF的文章就介紹到這了,更多相關(guān)python pdfkit將HTML轉(zhuǎn)換為PDF內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論