[Fixed] Make electron app allow pdf file downloading from local file system

Issue

I am working on small assignment where i need to make electron app show save file dialog and allow user to save pdf files (which are already stored in user app data folder). My application works like:

  1. User download zipped folder from the website (this folder contain all the data user need, like html, content, and pdf’s)
  2. User drop the zipped folder onto electron app to see all the downloaded content
  3. Now there’s download file button which imitate the action of downloading file from server (however, to make optimum utilization of server resources I zipped all the requried content into single zipped folder which user already downloaded to prevent server round trips)
  4. Now I want to show those locally saved pdf’s (inside user data folder)

I tried window.open(‘file:///file-path’), it doesn’t work. I got the error message that cannot show file. (due to security issues)

Solution

After trying multiple options like:

  • Adding anchor tag with href pointing to the relative path of pdf, it doesn’t show the pdf content in electron. Failed
  • Tried window.open function, it failed due to security issues
  • Finally, I learned that all the files opened in electron are saved in users/AppData/Roaming/’application name’/ and interestingly electron app can access all the content inside this location (since user manually dropped files there). So I used the fs node package to read file and show the save file dialog.

E.g.

var app = require('electron'),
    dialog = app.dialog,
    fs = require('fs');

var pdfContent = fs.readFileSync(app.GetPath('UserData'));
dialog.showSaveDialog({ title: 'app'}, pdfContent, function(err){ /*show error*/});
//something like this

Leave a Reply

(*) Required, Your email will not be published