LeeTee LeeTee - 3 months ago 27
Javascript Question

Node.js - download and save PDF file locally for offline - file damaged

I currently have a desktop App built with Node Webkit. When the user is online, the App will open up PDF files from the server. I then save these files locally so they are available when offline.

I am using the Node.js File System's fs.writeFile(), to save the PDF locally but when trying to open it via the App the PDF is blank. When I try to open it direct from the folder I get the below error.

enter image description here

Can anyone please advise?

//save PDF file for offline
function saveFile(pdfvar) {
var filename = 'test.pdf';
fs.writeFile(filename, pdfvar);
}

//open PDF in new window
$('#stage').on('click', '#pdflink', function(event){
var pdfvar = (this.getAttribute('data-pdffile'));
window.open(pdfvar, "_blank");
if(online===true){
saveFile(pdfvar);
}
});

Answer
  1. Are you holding entire content of a PDF in a DOM element attribute this.getAttribute('data-pdffile') ? This is where it may get corrupted.

  2. When you call

    window.open(pdfvar, "_blank");
    

the content is not ready to be opened like that. It should be first converted to base64 encoded url.

window.open('data:application/pdf,' + escape(pdfvar)); 

UPDATE:

The actual problem was that the OP was trying to save the file using it's URL in "pdfvar"

fs.writeFile(filename, pdfvar);

but the file created was containing only a URL itself. What was required was downloading the file first using a http library: