Warm tip: This article is reproduced from stackoverflow.com, please click
pyqt pyqt5 python pdfjs qprinter

Pdfjs print button does not work with PyQt5

发布于 2020-03-27 10:27:01

Straight to issue, when pdf loads with pdfjs into pyqt5, seems print button does not work correctly, also the same for download button.

How could this bug be fixed?

The code:

import sys
from PyQt5 import QtCore, QtWidgets, QtGui, QtWebEngineWidgets

PDFJS = 'file:///pdfjs/web/viewer.html'
PDF = 'file:///file0.pdf'
class PdfReport(QtWebEngineWidgets.QWebEngineView):
    def __init__(self, parent=None):
        super(PdfReport, self).__init__(parent)
        self.load(QtCore.QUrl.fromUserInput('%s?file=%s' % (PDFJS, PDF)))  

    def sizeHint(self):
        return QtCore.QSize(640, 480)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    im = PdfReport()
    im.show()
    sys.exit(app.exec_())

Display:

enter image description here

Any idea how to fix that?

Questioner
Pavel.D
Viewed
102
eyllanesc 2019-07-04 13:27

The print task is not enabled in Qt WebEngine so the fault is displayed (I'm still trying to get the data). But in the case of the download button of the PDF it is possible and for this you must use the downloadRequested signal of the QWebEngineProfile:

import os
import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets

CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))

PDFJS = QtCore.QUrl.fromLocalFile(
    os.path.join(CURRENT_DIR, "pdfjs/web/viewer.html")
).toString()


class PdfReport(QtWebEngineWidgets.QWebEngineView):
    def __init__(self, parent=None):
        super(PdfReport, self).__init__(parent)
        QtWebEngineWidgets.QWebEngineProfile.defaultProfile().downloadRequested.connect(
            self.on_downloadRequested
        )

    def load_pdf(self, filename):
        url = QtCore.QUrl.fromLocalFile(filename).toString()
        self.load(QtCore.QUrl.fromUserInput("%s?file=%s" % (PDFJS, url)))

    def sizeHint(self):
        return QtCore.QSize(640, 480)

    @QtCore.pyqtSlot(QtWebEngineWidgets.QWebEngineDownloadItem)
    def on_downloadRequested(self, download):
        path, _ = QtWidgets.QFileDialog.getSaveFileName(
            self, "Save File", "sample.pdf", "*.pdf"
        )
        if path:
            download.setPath(path)
            download.accept()


if __name__ == "__main__":

    app = QtWidgets.QApplication(sys.argv)
    w = PdfReport()
    path = os.path.join(CURRENT_DIR, "file0.pdf")
    w.load_pdf(path)
    w.show()
    sys.exit(app.exec_())