Download pdf files


Hi, i’m new to electron and i want to know how can i permit users to download a pdf file from a given URL. Thanks!


Being node.js based, Electron has access to the ‘fs’ file system API.

You can bring that in using var fs = require('fs');

Then you’ll want to do an AJAX request (jQuery’s pretty good for this, in which case you’ll also want this: window.$ = window.jQuery = require('./js/jquery.js');). Then in your request’s AJAX callback you want to use fs.writeFile something like this:
$.ajax({ url: url, success: function(data){ fs.writeFile(__dirname+"example.pdf", data, successCallback); } });

__dirname is a node.js global pointing at where your JavaScript is running from.


Didn’t work for me, it saves a blank pdf file.
Any Solution?


Sorry about that. I never tested it when I responded, and assumed that the code I was using for JSON would also work for PDF, but after trying it I can see that I’m also getting blank PDFs.

It’s something that I’m going to want to do anyway, so I’ll have a look into it, but I think it’s just an issue with how the data is handled before being piped into fs. I think there’s just a step missing.


fs.writeFile defaults the encoding to UTF-8. You might try setting it binary; e.g. fs.writeFile(file, data, 'binary', callback)


Thanks, but it’s still not working for me. I was trying to work out how to do it on the XHR side, but I even looked at local permissions. I’d not tried this yet though.

I often find myself caught out by Node documentation’s vagueness…

Interestingly, it does seem to pick up the size and orientation, but I can see in the metadata that everything’s slightly borked.


So I’ve gone back to my functions for downloading and it turned out that almost everything was busted. I’ve now got it all working, including for PDFs:

var r = new XMLHttpRequest();"GET", url, true);
r.onload = function(e){
    var data=new Buffer(r.response);
         data, successCallback