Python 3.x 使用pyqt5将html转换为pdf而不显示屏幕
我正在尝试使用以下代码使用QtWebEngineWidgets将html呈现为pdfPython 3.x 使用pyqt5将html转换为pdf而不显示屏幕,python-3.x,pyqt5,Python 3.x,Pyqt5,我正在尝试使用以下代码使用QtWebEngineWidgets将html呈现为pdf import sys from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets from tempfile import gettempdir from pathlib import Path def printhtmltopdf(html_in, callback): tfile =Path(gettempdir(), 'printhtmltop
import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
from tempfile import gettempdir
from pathlib import Path
def printhtmltopdf(html_in, callback):
tfile =Path(gettempdir(), 'printhtmltopdf.html')
with open(tfile, 'wb') as tempf:
tempf.write(html_in)
app = QtWidgets.QApplication(sys.argv)
loader = QtWebEngineWidgets.QWebEngineView()
loader.setZoomFactor(1)
loader.page().pdfPrintingFinished.connect(
lambda *args: print('finished:', args))
loader.load(QtCore.QUrl().fromLocalFile(str(tfile)))
def emit_pdf(finished):
loader.page().printToPdf(callback)
app.exit(0)
loader.loadFinished.connect(emit_pdf)
app.exec()
但是,回调从未触发。当我省略app.exit(0)时,它会工作,但它会等待我不想要的用户交互。事实上,我更愿意在不使用eventloop的情况下执行例程。您必须使用QWebEnginePage,也不需要创建临时文件,但您可以直接加载HTML:
从PyQt5导入QtCore、qtwidget、QtWebEngineWidgets
def printhtmltopdf(html_-in,pdf_文件名):
app=QtWidgets.QApplication([])
page=QtWebEngineWidgets.QWebEnginePage()
def句柄\u pdfPrintingFinished(*args):
打印(“已完成:”,args)
app.quit()
def句柄_加载完成(已完成):
第页printToPdf(pdf_文件名)
page.pdfPrintingFinished.connect(句柄\u pdfPrintingFinished)
page.loadFinished.connect(handle\u loadFinished)
第页setZoomFactor(1)
page.setHtml(html_-in)
app.exec()
printhtmltopdf(
"""
你好
你好,世界!
这是一个简单的段落
""",
“test.pdf”,
)
@DickKniep如果我的答案对您有帮助,请不要忘记将其标记为正确,如果您不知道如何做,请检查