Pdfjs打印按钮不适用于PyQt5

时间:2019-07-03 14:58:03

标签: python pyqt pyqt5 pdfjs qprinter

直接发布,当pdf与pdfjs一起加载到pyqt5中时,似乎打印按钮无法正常工作,下载按钮也是如此。

如何修复此错误?

代码:

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

显示

enter image description here

有什么办法解决吗?

2 个答案:

答案 0 :(得分:2)

Qt WebEngine中未启用打印任务,因此显示了错误(我仍在尝试获取数据)。但是使用PDF的下载按钮是可能的,为此,您必须使用downloadRequestedQWebEngineProfile信号:

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

答案 1 :(得分:0)

这不是PyQt5按钮,而是Web视图中的按钮。由于您的webView对象或代码的Web部分缺少该按钮的功能,因此可能无法正常工作。