Qt 5.8 和 Pdf.js 错误

Qt 5.8 and Pdf.js error

我在使用 pdf.js 和 Qt 5.8 时遇到问题,我尝试在我的应用程序 link Using pdf.js with Qt5.8 中执行相同的代码,但他不工作我不知道为什么,qt 给我看这条关于 JS 的消息:

"js: Uncaught TypeError: Cannot read property 'PDFJS' of undefined".

这是我在主窗口中的代码:

QWebEngineView *view;
QString pdfFileURL;

QString pathToPDFjs = QString("file:///"+qApp->applicationDirPath()+"/libraries/PDF/viewer.html");

pdfFileURL = "file:///C:/Users/Administrateur/Desktop/CV.pdf";

view = new QWebEngineView();
this->setCentralWidget(view);

view->load(QUrl::fromUserInput(pathToPDFjs + QString("?file=") + pdfFileURL));
view->show();

我建议从 here 下载源代码。

然后将整个文件复制到项目中的一个文件夹中(在我的例子中是 3rdParty):

.
├── 3rdParty
│   └── pdfjs-1.7.225-dist
│       ├── build
│       │   ├── pdf.js
│       │   └── pdf.worker.js
│       ├── LICENSE
│       └── web
│           ├── cmaps
│           ├── {another files}
│           ├── viewer.css
│           ├── viewer.html
│           └── viewer.js
├── CV.pdf
├── main.cpp
├── mainwindow.cpp
├── mainwindow.h
├── mainwindow.ui
└── pdfjsExample.pro

另一个建议是在 .pro 中创建一个命令,这样您就可以将库复制到可执行文件的一侧并且没有文件夹位置的问题(其中 CV.pdf 是我用来做的 pdf测试)。

COPY_CONFIG = 3rdParty CV.pdf
copy_cmd.input = COPY_CONFIG
copy_cmd.output = ${QMAKE_FILE_IN_BASE}${QMAKE_FILE_EXT}
copy_cmd.commands = $$QMAKE_COPY_DIR ${QMAKE_FILE_IN} ${QMAKE_FILE_OUT}
copy_cmd.CONFIG += no_link_no_clean
copy_cmd.variable_out = PRE_TARGETDEPS
QMAKE_EXTRA_COMPILERS += copy_cmd

代码如下所示:

QWebEngineView *view;
QString pdfFileURL;

QString pathToPDFjs = QString("file:///%1/%2")
        .arg(QDir::currentPath())
        .arg("3rdParty/pdfjs-1.7.225-dist/web/viewer.html");

pdfFileURL = QString("file:///%1/%2").arg(QDir::currentPath()).arg("CV.pdf");

view = new QWebEngineView();
setCentralWidget(view);

QUrl url = QUrl::fromUserInput(pathToPDFjs + QString("?file=") + pdfFileURL);

view->load(url);

注意:将 applicationDirPath 修改为 CurrentPath,这样如果我将可执行文件移动到另一个位置我就不会产生问题,为了使应用程序正常工作,3rdParty 文件夹和我们的可执行文件必须在一起。

完整代码为here.

如果你想隐藏打印按钮和打开按钮,你应该注释以下行:

viewer.html [第 178 行]

<!--button id="openFile" class="toolbarButton openFile hiddenLargeView" title="Open File" tabindex="32" data-l10n-id="open_file">
  <span data-l10n-id="open_file_label">Open</span>
</button>

<button id="print" class="toolbarButton print hiddenMediumView" title="Print" tabindex="33" data-l10n-id="print">
  <span data-l10n-id="print_label">Print</span>
</button-->

viewer.js [第 3058 行]

  /*items.openFile.addEventListener('click', function (e) {
    eventBus.dispatch('openfile');
  });
  items.print.addEventListener('click', function (e) {
   eventBus.dispatch('print');
  });*/