溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么用python包pdfkit將HTML轉(zhuǎn)換為PDF

發(fā)布時間:2022-04-21 13:41:02 來源:億速云 閱讀:216 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容介紹了“怎么用python包pdfkit將HTML轉(zhuǎn)換為PDF”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!

    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

    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

    “怎么用python包pdfkit將HTML轉(zhuǎn)換為PDF”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

    向AI問一下細節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI