安裝wkhtmltopdf?
網站:wkhtmltopdf
wkhtmltopdf http://www.baidu.com/ D:website1.pdf
安裝pdfkit庫
pip install pdfkit
批量轉換代碼
import os
import pdfkit
path_wkthmltopdf = r'E:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)def convert_html_to_pdf(input_folder, output_folder):# 確保輸出文件夾存在if not os.path.exists(output_folder):os.makedirs(output_folder)# 遍歷輸入文件夾及其子文件夾中的所有文件for root, dirs, files in os.walk(input_folder):for file in files:if file.endswith(".htm"):html_file_path = os.path.join(root, file)pdf_file_path = os.path.join(output_folder, file.replace('.htm', '.pdf'))try:# 使用pdfkit將HTML文件轉換為PDF文件pdfkit.from_file(html_file_path, pdf_file_path,configuration=config, options={'encoding': 'utf-8',"enable-local-file-access":True})print(f"成功轉換: {html_file_path} -> {pdf_file_path}")except Exception as e:print(f"轉換失敗: {html_file_path} -> {pdf_file_path}, 錯誤信息: {e}")if __name__ == "__main__":input_folder = 'D:\' # 輸入文件夾路徑,這里設置為當前目錄output_folder = 'D:\pdf' # 輸出文件夾路徑convert_html_to_pdf(input_folder, output_folder)
報錯解決
Python OSError: wkhtmltopdf reported an error:Exit with code 1 due to network error:ProtocolUnknownE_exit with code 1 due to network error: protocolunk-CSDN博客
參考
pdfkit | 利用python實現html文件轉pdf (zhihu.com)
Python OSError: wkhtmltopdf reported an error:Exit with code 1 due to network error:ProtocolUnknownE_exit with code 1 due to network error: protocolunk-CSDN博客