简体   繁体   中英

Pdfjs print button does not work with PyQt5

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:

在此处输入图片说明

Any idea how to fix that?

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_())

That's not a PyQt5 button, that is a button from your web view. It may not work because of your webView object or because the web part of your code lacks functionality for the button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM