pythonhtmlbrowserpyqt5qprinter

How to use pyqt5 browser to Realize printing function


when I use pyqt5 browser to Visit specific web pages ,in this pages has a print button,but when I click this print button the browser has no response.in Firefox browser,after I click print button,the printpreview is showing,and the i can choose printer.


Solution

  • According to this, print preview is not yet available for QtWebEngine, so you can only directly print.

    To catch the print request of a page, you need to connect the printRequested() signal.

    class PrintTest(QtWidgets.QWidget):
        def __init__(self, parent=None):
            super(PrintTest, self).__init__(parent)
            layout = QtWidgets.QHBoxLayout(self)
            self.view = QtWebEngineWidgets.QWebEngineView()
            layout.addWidget(self.view)
            self.page = QtWebEngineWidgets.QWebEnginePage(self)
            self.view.setPage(self.page)
            self.page.printRequested.connect(self.printRequested)
            # load a page that has a print request
            self.view.load(QtCore.QUrl(
                "https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_print"))
    
        def printRequested(self):
            defaultPrinter = QtPrintSupport.QPrinter(
                QtPrintSupport.QPrinterInfo.defaultPrinter())
            dialog = QtPrintSupport.QPrintDialog(defaultPrinter, self)
            if dialog.exec():
                # printer object has to be persistent
                self._printer = dialog.printer()
                self.page.print(self._printer, self.printResult)
    
        def printResult(self, success):
            if success:
                QtWidgets.QMessageBox.information(self, 'Print completed', 
                    'Printing has been completed!', QtWidgets.QMessageBox.Ok)
            else:
                QtWidgets.QMessageBox.warning(self, 'Print failed', 
                    'Printing has failed!', QtWebEngineWidgets.QMessageBox.Ok)
                self.printRequested()
            del self._printer