使用 wkhtmltopdf 将多个 HTML 文件转换为 PDF

问题描述 投票:0回答:1

我尝试按照教程并通过 Python 编写一些程序来将 HTML 文件转换为 PDF。 在我的例子中是“sample.html”。

import pdfkit

#Define path to wkhtmltopdf.exe
path_to_wkhtmltopdf = r'C:\Program Files\wkhtmltopdf\bin\wkthmltopdf.exe'

#Define path to HTML file
path_to_file = 'sample.html'

#Point pdfkit configuration to wkhtml.exe
config = pdfkit.configuration(wkhtmltopdf = path_to_wkhtmltopdf)

#Convert HTML file to PDF
pdfkit.from_file(path_to_file, output_path = 'sample.pdf', configuration = config)

但是现在我有一个包含许多 HTML 文件的文件夹,单独为每个文件执行此操作会带来太多工作量。我需要更改代码的哪一部分才能实现此目的?

html pdf converters wkhtmltopdf html-to-pdf
1个回答
0
投票

我在下面添加示例代码。

import os
import pdfkit

path_to_wkhtmltopdf = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'
html_folder_path = r'path/to/html/files'
config = pdfkit.configuration(wkhtmltopdf=path_to_wkhtmltopdf)
html_files = [file for file in os.listdir(html_folder_path) if file.endswith('.html')]

for html_file in html_files:
    input_html_path = os.path.join(html_folder_path, html_file)
    output_pdf_path = os.path.join(html_folder_path, f'{os.path.splitext(html_file)[0]}.pdf')

    pdfkit.from_file(input_html_path, output_path=output_pdf_path, configuration=config)

print("Conversion completed.")
© www.soinside.com 2019 - 2024. All rights reserved.