Download pdf files


#1

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!


#2

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.


#3

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


#4

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.


#5

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


#6

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.


#7

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();
r.open("GET", url, true);
r.responseType='arraybuffer';
r.onload = function(e){
    var data=new Buffer(r.response);
    fs.writeFile(
         __dirname+'example.pdf',
         data, successCallback
    );
}
r.send();