python pdfkit生成PDF


pdfkit與wkhtmltopdf介紹

pdfkit

pdfkit,把HTML+CSS格式的文件轉換成PDF格式文檔的一種工具。

wkhtmltopdf

pdfkit是基於wkhtmltopdf的python封裝,支持URL,本地文件,文本內容到PDF的轉換,所以使用pdfkit需要下載wkhtmltopdf。

三步實現自動生成pdf文檔

1.使用pip安裝pdfkit

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

pip install pdfkit
 
2.安裝wkhtmltopdf.exe文件
注意:下載后安裝,記住安裝路徑。
 
3.使用pdfkit庫生成pdf文件
pdfkit可以將 網頁、html文件、字符串生成pdf文件。
網頁生成 pdf( pdfkit.from_url()
# 導入庫
import pdfkit

'''將網頁生成pdf文件'''
def url_to_pdf(url, to_file):
    # 將wkhtmltopdf.exe程序絕對路徑傳入config對象
    path_wkthmltopdf = r'文件路徑'
    config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)
    # 生成pdf文件,to_file為文件路徑
    pdfkit.from_url(url, to_file, configuration=config)
    print('完成')

url_to_pdf(r'url', '輸出文件名.pdf')

html 文件生成 pdf(pdfkit.from_file()

# 導入庫
import pdfkit

'''將html文件生成pdf文件'''
def html_to_pdf(html, to_file):
    # 將wkhtmltopdf.exe程序絕對路徑傳入config對象
    path_wkthmltopdf = r'文件路徑'
    config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)
    # 生成pdf文件,to_file為文件路徑
    pdfkit.from_file(html, to_file, configuration=config)
    print('完成')

html_to_pdf('html文件名.html','輸出文件名.pdf')

字符串生成 pdf(pdfkit.from_string())

# 導入庫
import pdfkit

'''將字符串生成pdf文件'''
def str_to_pdf(string, to_file):
    # 將wkhtmltopdf.exe程序絕對路徑傳入config對象
    path_wkthmltopdf = r'文件路徑'
    config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)
    # 生成pdf文件,to_file為文件路徑
    pdfkit.from_string(string, to_file, configuration=config)
    print('完成')

str_to_pdf('字符串','輸出文件名.pdf')


免責聲明!

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



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