1 回答
TA贡献1859条经验 获得超6个赞
您必须使用 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")
添加回答
举报