View PDF in electron BrowserWindow

2019-03-04 04:13发布

问题:

Now before you flag this as a duplicate I know that there are those:

  • Electron PDF viewer
  • how to open a local pdf file in an app built with electron
  • How to embed a pdf file in electron
  • opening pdf files in electron

and I've read all of them thoroughly and commented on some of them but none of the solutions there seem applicable.

So I have this electron app and in one of the .html-files I link another script that provides some utility-functions to the program and one of those is this one:

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

So this should use the integrated PDF-Viewer of Electron (which uses Chromium) to open the PDF in a new window. I used the infamous plugins: true, I tried through most of the thousands of preferences you can define for a BrowserWindow but it always opens the window and then starts to download the file instead of displaying it.

I triple checked the filepath, the "imports" etc., updated everything but I can't seem to find the problem. Electron natively supports this since 1.6.4 but it doesn't work for me.

Help me, Stack Overflow, you are my only hope.

回答1:

@karthick correctly pointed out that this is a bug which disables the plugins despite plugins: true. It exists since 3.0.0 and remains to be fixed today: Issue on GitHub.

Knowing this I could successfully make it work by downgrading to the latest 2.X.X. To do that you have to change the devDependencies in the package.json which should be found in your project folder.

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

Alternatively you could call on the system to open the file. It will choose the default program assigned to PDFs:

shell.openItem(fullPath);

Just make sure that the path (fullPath) is always correctly resolved with something like path.resolve(app.getAppPath(), filePath) as it might change when you build the app.