代码之家  ›  专栏  ›  技术社区  ›  leonheess

在electron Browser窗口中查看PDF

  •  0
  • leonheess  · 技术社区  · 7 年前

    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
        });
    }
    

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

    我三次检查了文件路径,“导入”等,更新了一切,但我似乎找不到问题。电子本身就支持这一点,因为 1.6.4 但这对我没用。

    1 回复  |  直到 6 年前
        1
  •  25
  •   leonheess    5 年前

    更新2020:

    @karthick正确地指出,这是一个错误,尽管 plugins: true The Issue 存在 since 3.0.0 终于在第9版中修复了!

    npm update electron
    

    你可以查一下 devDependencies package.json 应该在项目文件夹中找到。应该是这样的:

    "devDependencies": {
        "electron": "^9.0.0"
    },
    

    由于持久的GitHub问题往往变得相当混乱,我将用开发的要点更新这个答案。你也可以在答案的末尾找到三个解决方法。

    更新:

    1. 3月19日: A fix is on the way
    2. 5月19日:上述修复目前处于搁置状态 等待 better extension support .
    3. Better extension support 预计不会很快到达那里。
    4. The fix 不再积极参与。引用 开发商名称:

    我在尝试移植Chromium的查看器时遇到的主要问题是它对Chromium扩展系统的依赖性。Electron只支持该系统的一部分,这使得它很难集成查看器。

    1. 7月25日:这方面取得了重大进展 improvement of the extension support 合并后的 follow-up tracking issue 已创建。这增加了继续进行这项工作的可能性 the fix .

    2. 8月28日:现在没有人在修复。你可以 put a bounty on this issue over on BountySource 如果你想更快的解决这个问题。

    3. 已关闭,分支已删除。开发商报价:

    我们仍打算有朝一日恢复PDF查看器,但它依赖于我们首先迁移到使用Chrome的扩展库而不是我们自己的shim,因为Chrome中的PDF查看器是作为扩展实现的。

    1. a bounty of $1,600 over on BountySource

    2. tracking issue )和一个 new fix 已引入。

    3. 2月13日: The new fix 已合并,问题已解决。 看来这将在电子10中被解决! 开发商报价:

    解决方法:

    1.  npm install electron@"<3.0.0" --save-dev
      

    only the latest three stable major versions are supported by the Electron team 这意味着 2.X.X不再接收安全补丁 .

    1. 或者,您可以调用系统打开该文件。它将选择分配给PDF的默认程序:

       shell.openItem(fullPath);
      

    只要确保这条路( fullPath path.resolve(app.getAppPath(), filePath) 因为当你构建应用程序时它可能会改变。

    1. PDF.js 它并没有提供ChromePDF浏览器的全部功能(例如缺少字段补全),但对于大多数应用程序来说可能已经足够了。下面是一个示例实现,它捕获下载事件并将其路由到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()}`));
           }
       })