1

I want to use Python to convert some html files to PDF. After looking at the modules and possibilities to do this, I settled on Qt5.

I have code that works, but it doesn't work exactly how I want. I want to run my program via the command line, and it to exit once finished. Currently, it produces the PDF but stays running.

If I uncomment and show the QWebEngineView with view.show(), then I can close the window that opens and the program will exit. (But I don't want to have any GUI, so this isn't good)

Next, I tried to show the view, then immediately close it after with view.close(), but when I do this a PDF doesn't get generated. I tried adding a 5 second sleep after view.show() and before view.close(), but still the same result.

I'm not sure if what I want is possible, I understand Qt is for GUIs but it would be very convenient if I could get this working completely through the command line.

import sys import os from time import sleep from PyQt5.QtWidgets import QApplication from PyQt5.QtWebEngineWidgets import QWebEngineView from PyQt5.QtCore import QDir, QUrl # needed to load local html files sys.argv.append("--disable-web-security") app = QApplication(sys.argv) raw_html = "" with open('webpage.htm', 'r') as myfile: raw_html = myfile.read() view = QWebEngineView() view.setHtml(raw_html) def save_pdf(finished): view.page().printToPdf("output.pdf") # view.show() # view.close() view.loadFinished.connect(save_pdf) sys.exit(app.exec_()) 
1
  • what is your pyqt version? Commented Nov 9, 2018 at 14:47

1 Answer 1

2

Try it:

import sys from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets app = QtWidgets.QApplication(sys.argv) loader = QtWebEngineWidgets.QWebEngineView() loader.setZoomFactor(1) loader.page().pdfPrintingFinished.connect(loader.close) # <--- 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() 
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, but: AttributeError: 'QWebEnginePage' object has no attribute 'pdfPrintingFinished'
@BenKailon update your pyqt5, the pdfPrintingFinished signal was recently implemented in Qt 5.9
@eyllanesc ah it was 5.8.1, I didn't even think about that. Sorry. Now, after updating, I get a different error. ImportError: cannot import name 'QtWebEngineWidgets' After a little research it looks like the 32 bit Windows PyQt5 wheels that pip installs don't have QtWebEngineWidgets anymore... This is getting complicated!
Just a win32 issue, but after downgrading pyqt5 to 5.10, it's working perfectly. Thanks to both of you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.