繁体   English   中英

QWebEngineView 无法呈现嵌入在 HTML 中的 PDF

[英]QWebEngineView fails to render PDF embedded in HTML

I'm writing a Python script for an MDI-based PyQt5 application, where the windows use the new QWebEngineView to render some HTML that embeds a PDF in an iFrame. HTML 是自定义生成的字符串,PDF 是本地文件。

HTML 是一个本地存储的模板,我的代码加载它,然后更改以插入一个变量:

<!DOCTYPE html>
<html>
  <head>
    <title>Title</title>
  </head>
  <body>
    <iframe src="$PDF">
    </iframe>
  </body>
</html>

$PDF 被替换为字符串,例如:file:///local/path/to/document.pdf

到目前为止,这是我的 Python 脚本:

import os, sys
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication, QMainWindow, QMdiArea, QAction, QMdiSubWindow
from PyQt5 import QtWebEngineWidgets

class MDIWindow(QMainWindow):

    def __init__(self):
        super().__init__()

        self.mdi = QMdiArea()
        self.setCentralWidget(self.mdi)
        bar = self.menuBar()
        file = bar.addMenu("File")
        file.addAction("New")
        file.addAction("cascade")
        file.addAction("Tiled")
        file.triggered[QAction].connect(self.Window)
        self.setWindowTitle("MDI Application")

    def Window(self, p):
        if p.text() == "New":
            sub = QMdiSubWindow()
            view = QtWebEngineWidgets.QWebEngineView()
            settings = view.settings()
            settings.setAttribute(QtWebEngineWidgets.QWebEngineSettings.PluginsEnabled, True)
            CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
            pdf_path = "file://" + os.path.join(CURRENT_DIR, "test.pdf")
            template = os.path.join(CURRENT_DIR, "test.html")
            with open(template, 'rt') as f:
                text = ''.join(f.readlines())
                html = text.replace('$PDF', pdf_path)
            view.setHtml(html, QUrl("file://"))
            sub.setWidget(view)
            sub.setWindowTitle("Test")
            self.mdi.addSubWindow(sub)
            sub.show()

        if p.text() == "cascade":
            self.mdi.cascadeSubWindows()

        if p.text() == "Tiled":
            self.mdi.tileSubWindows()

app = QApplication([])
mdi = MDIWindow()
mdi.show()
app.exec_()

该脚本的大部分工作正常 - 它创建主 window,接收菜单栏命令以创建文档 window,创建文档 window,并加载 Z05B8C74AD1FCA207. 都好。

问题是嵌入式 PDF 不会加载。 我得到的只是一个灰色的表面。

进一步的观察:

  • 插入到页面中的任何 HTML 视觉元素都会正确呈现。

  • 将资源类型更改为图像(例如 PNG)会导致资源正确呈现。 只是PDF有问题。

  • 如果我将文件 URL 更改为其他内容,我会收到有关死链接的警告。 所以它显然是在尝试加载 PDF。

  • 实际的 PDF 无关紧要 - 我尝试了几个不同的结果相同。

  • 灰色表面提供了一个包含重新加载、保存页面和查看源代码的上下文菜单。 重新加载显然确实会导致页面刷新(它会短暂闪烁)但会产生相同的结果。 保存页面和查看源代码什么都不做。

有任何想法吗? 提前致谢。

It seems to be a Qt WebEngine bug( QTBUG-84340 ) since I have implemented the code with Qt 5.15 (and PyQt5 5.15 and PyQtWebEngine 5.15) and it does not load the pdf. 相反,我已经使用 PyQt5 5.14.2 和 PyQtWebEngine 5.14.0 对其进行了测试,因此我建议您安装这些软件包:

python -m pip install pyqt5==5.14.2 pyqtwebengine==5.14.0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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