如何使用 PyQt5 将本地 html 文件转换为 pdf?
How to convert a local html file to pdf using PyQt5?
我曾尝试使用 wkhtml 和 weasyprint 库,但所有这些库都呈现空白 pdf 页面。唯一可行的选项是 pdfcrowd,但这是一个付费图书馆。我找到了几个使用 PyQt 转换网页的选项:
import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
app = QtWidgets.QApplication(sys.argv)
loader = QtWebEngineWidgets.QWebEngineView()
loader.setZoomFactor(1)
loader.page().pdfPrintingFinished.connect(
lambda *args: print('finished:', args))
loader.load(QtCore.QUrl('https://en.wikipedia.org/wiki/Main_Page'))
def emit_pdf(finished):
loader.show()
loader.page().printToPdf("test.pdf")
loader.loadFinished.connect(emit_pdf)
app.exec()
但是,我不太确定如何将其适应本地保存的 html 文件。
您必须使用 QUrl.fromLocalFile() 将文件路径作为 url 传递,也没有必要创建 QWebEngineView,只需使用 QWebEnginePage:
import os
import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
def html_to_pdf(html, pdf):
app = QtWidgets.QApplication(sys.argv)
page = QtWebEngineWidgets.QWebEnginePage()
def handle_print_finished(filename, status):
print("finished", filename, status)
QtWidgets.QApplication.quit()
def handle_load_finished(status):
if status:
page.printToPdf(pdf)
else:
print("Failed")
QtWidgets.QApplication.quit()
page.pdfPrintingFinished.connect(handle_print_finished)
page.loadFinished.connect(handle_load_finished)
page.load(QtCore.QUrl.fromLocalFile(html))
app.exec_()
if __name__ == "__main__":
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
filename = os.path.join(CURRENT_DIR, "index.html")
print(filename)
html_to_pdf(filename, "test.pdf")
我曾尝试使用 wkhtml 和 weasyprint 库,但所有这些库都呈现空白 pdf 页面。唯一可行的选项是 pdfcrowd,但这是一个付费图书馆。我找到了几个使用 PyQt 转换网页的选项:
import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
app = QtWidgets.QApplication(sys.argv)
loader = QtWebEngineWidgets.QWebEngineView()
loader.setZoomFactor(1)
loader.page().pdfPrintingFinished.connect(
lambda *args: print('finished:', args))
loader.load(QtCore.QUrl('https://en.wikipedia.org/wiki/Main_Page'))
def emit_pdf(finished):
loader.show()
loader.page().printToPdf("test.pdf")
loader.loadFinished.connect(emit_pdf)
app.exec()
但是,我不太确定如何将其适应本地保存的 html 文件。
您必须使用 QUrl.fromLocalFile() 将文件路径作为 url 传递,也没有必要创建 QWebEngineView,只需使用 QWebEnginePage:
import os
import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
def html_to_pdf(html, pdf):
app = QtWidgets.QApplication(sys.argv)
page = QtWebEngineWidgets.QWebEnginePage()
def handle_print_finished(filename, status):
print("finished", filename, status)
QtWidgets.QApplication.quit()
def handle_load_finished(status):
if status:
page.printToPdf(pdf)
else:
print("Failed")
QtWidgets.QApplication.quit()
page.pdfPrintingFinished.connect(handle_print_finished)
page.loadFinished.connect(handle_load_finished)
page.load(QtCore.QUrl.fromLocalFile(html))
app.exec_()
if __name__ == "__main__":
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
filename = os.path.join(CURRENT_DIR, "index.html")
print(filename)
html_to_pdf(filename, "test.pdf")