因此,我有了这个Electron应用程序,并且在一个.html文件中,我链接了另一个脚本,该脚本为该程序提供了一些实用程序功能,其中一个是这个:

function openPDF(filePath){
    let pdfWindow = new electron.remote.BrowserWindow({
        icon: './build/icon.png',
        width: 1200,
        height: 800,
        webPreferences: {
            plugins: true
        }
    });

    pdfWindow.loadURL(url.format({
        pathname: filePath,
        protocol: 'file:',
        slashes: true
    }));

    pdfWindow.setMenu(null);

    pdfWindow.on("closed", function () {
        pdfWindow = null
    });
}

因此,这应该使用集成的 Electron PDF查看器(使用Chromium)在新窗口中打开PDF。我使用了臭名昭著的plugins: true,我尝试了大多数的thousands of preferences you can define for a BrowserWindow,但是它总是打开窗口,然后开始下载文件而不显示它。

我三重检查了文件路径,“导入”等,更新了所有内容,但似乎找不到问题。自1.6.4起,Electron本身就支持此功能,但它对我不起作用。

帮我,Stack Overflow,您是我唯一的希望。

最佳答案

2020年更新:
@karthick正确指出,尽管有plugins: true,这是一个禁用插件的错误。 The Issue存在since 3.0.0(2018年9月18日),今天仍然需要修复。终于在版本9中得到修复!
使用以下命令将 Electron 版本更新为9.X.X或更高版本以启用功能:

npm update electron
您可以在项目文件夹中的devDependencies中检查package.json。它看起来应该像这样:
"devDependencies": {
    "electron": "^9.0.0"
},

旧答案:
由于长期存在的GitHub问题趋于令人困惑,因此我将根据开发的要点来更新此答案。您还可以在答案末尾找到三种解决方法。
更新:
  • 3月19日:A fix is on the way
  • 5月19日:上述修复程序目前处于暂停状态
    等待better extension support
  • 6月28日:预计Betterextension support不会很快出现。
  • 7月16日:The fix不再处于事件状态。引用
    开发人员:


  • 7月25日:合并的improvement of the extension support并创建了follow-up tracking issue取得了重大进展。这增加了继续进行the fix的可能性。
  • 8月28日:目前,没有人在进行修复。如果您想更快地解决此问题,可以使用put a bounty on this issue over on BountySource
  • 11月19日:The fix已关闭,分支已删除。开发商报价:


  • 1月2日:尽管a bounty of $1,600 over on BountySource,仍然没有人对此进行研究
  • 1月21日:扩展支持(tracking issue)不断得到改进,并且引入了new fix
  • 2月13日:The new fix已合并,问题已解决。 看起来这将在Electron 10中解决! 开发人员的报价:


  • 解决方法:
  • 您可以通过降级到最新的2.X.X使其工作。为此,请使用以下命令:
     npm install electron@"<3.0.0" --save-dev
    

  • 但是请记住,only the latest three stable major versions are supported by the Electron team意味着 2.X.X不再接收安全补丁
  • 或者,您可以调用系统来打开文件。它将选择分配给PDF的默认程序:
     shell.openItem(fullPath);
    

  • 只需确保始终使用fullPath之类的东西正确解析路径(path.resolve(app.getAppPath(), filePath)),因为在构建应用程序时它可能会更改。
  • 另一个解决方法是使用PDF.js之类的东西,它不能完全提供Chrome PDF Viewer的全部功能(例如缺少字段补全),但对于大多数应用程序来说可能已经足够了。这是一个示例实现,捕获下载事件并将其路由到PDF.js-viewer:
     const { BrowserWindow, session } = require('electron')
     session.defaultSession.on('will-download', (event, item, webContents) => {
         if (item.getMimeType() === 'application/pdf' && item.getURL().indexOf('blob:file:') != 0) {
             event.preventDefault();
             new BrowserWindow().loadFile(path.resolve(__dirname, `pdfjs/web/viewer.html?file=${item.getURL()}`));
         }
     })
    
  • 关于javascript - 如何在 Electron 浏览器窗口中查看PDF?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52844135/

    10-09 09:02