1

I'm trying to render an HTML file as a PDF with PyQt5. Unfortunately, my HTML page loads slow, but I couldn't find a way to wait for it to load. My question is this; How can I make PyQt5 wait for a couple of seconds, after resuming the execution? Or is there a better way to wait for JS scripts to execute?

app = QtWidgets.QApplication(sys.argv)
loader = QtWebEngineWidgets.QWebEngineView()
loader.setZoomFactor(1)
loader.page().pdfPrintingFinished.connect(loader.close)
loader.load(QtCore.QUrl(url))

def emit_pdf(finished):
    loader.page().printToPdf("test.pdf")
    
loader.loadFinished.connect(emit_pdf)
    
app.exec()

I tried using QTimer but couldn't make it work. Here is how it looked like.

app = QtWidgets.QApplication(sys.argv)
loader = QtWebEngineWidgets.QWebEngineView()
loader.setZoomFactor(1)
loader.page().pdfPrintingFinished.connect(loader.close)
loader.load(QtCore.QUrl(url))

timer = QtCore.QTimer()
timer.setInterval(2000)

def run_emit():
    loader.loadFinished.connect(emit_pdf)

timer.timeout.connect(run_emit)
timer.start()

def emit_pdf(finished):
    timer.stop()
    loader.page().printToPdf("test.pdf")
app.exec()
Ozgur O.
  • 97
  • 9
  • 1
    `def emit_pdf(finished): QTimer.singleShot(2000, lambda: loader.page().printToPdf("test.pdf"))`. – ekhumoro Oct 21 '21 at 16:35
  • I assume there is no better way to wait besides QTimer. This works, thank you! – Ozgur O. Oct 22 '21 at 08:51
  • I don't think there's any *completely general* way to know when the final resource accessed by the page has fully loaded. Many things will happen asynchronously, and some things may not happen at all (or at least extremely slowly). The best you can do is guesstimate an appropriate delay. – ekhumoro Oct 22 '21 at 12:22

1 Answers1

0

There is no Explicit wait for the final product. Instead of using QTimer.start() or QTimer.stop(), QTimer.singleShot() with a lambda function will work.

def emit_pdf(finished):
    QTimer.singleShot(2000, lambda: loader.page().printToPdf("test.pdf"))

app.exec()

I added this in case the solution comment is lost.

Ozgur O.
  • 97
  • 9