Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download pdf file from url in node.js?

I am creating an application to download pdf files from url and show in my dashboard page as grid wise.

I am using node.js with express framework.

exports.pdf = function(req, response) {
    var url ="http://www.ieee.org/documents/ieeecopyrightform.pdf";

    http.get(url, function(res) {
     var chunks = [];
     res.on('data', function(chunk) {
     console.log('start');
     chunks.push(chunk);
    });

    res.on("end", function() {
      console.log('downloaded');
      var jsfile = new Buffer.concat(chunks).toString('base64');
      console.log('converted to base64');
      response.header("Access-Control-Allow-Origin", "*");
      response.header("Access-Control-Allow-Headers", "X-Requested-With");
      response.header('content-type', 'application/pdf');
     response.send(jsfile);
    });
    }).on("error", function() {
   console.log("error");
   }); 
};
like image 269
abdulbarik Avatar asked Sep 20 '14 05:09

abdulbarik


1 Answers

For those looking to download a PDF server side, which is a bit of a different use case than the OP, here's how I did it using the request npm module:

const fs = require("fs");
const request = require("request-promise-native");

async function downloadPDF(pdfURL, outputFilename) {
    let pdfBuffer = await request.get({uri: pdfURL, encoding: null});
    console.log("Writing downloaded PDF file to " + outputFilename + "...");
    fs.writeFileSync(outputFilename, pdfBuffer);
}

downloadPDF("https://www.ieee.org/content/dam/ieee-org/ieee/web/org/pubs/ecf_faq.pdf", "c:/temp/somePDF.pdf");
like image 116
Ryan Shillington Avatar answered Oct 04 '22 18:10

Ryan Shillington