Skip to content

Instantly share code, notes, and snippets.

@adamgibbons
Last active December 22, 2022 17:38
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save adamgibbons/af2de54c011e68a7b85a to your computer and use it in GitHub Desktop.
Save adamgibbons/af2de54c011e68a7b85a to your computer and use it in GitHub Desktop.
Display or download PDF from node.js server
var restify = require('restify')
, port = process.env.PORT || 3000
, Phantom = require('phantom')
, tmpdir = require('os').tmpdir()
, fs = require('fs');
var server = restify.createServer();
function setResponseHeaders(res, filename) {
res.header('Content-disposition', 'inline; filename=' + filename);
res.header('Content-type', 'application/pdf');
}
server.get('/downloads/:filename', function(req, res, next) {
var filename = req.params.filename;
file = tmpdir + filename;
setResponseHeaders(res, filename);
Phantom.create(function(phantom) {
phantom.createPage(function(page) {
// Render PDF and send to browser
function dispatchPDF() {
page.render(file, function() {
fs.createReadStream(file).pipe(res);
phantom.exit();
});
};
page.set('content', "<p>hello i am content</p>");
page.set('paperSize', '5in');
page.set('onLoadFinished', dispatchPDF);
});
});
});
server.listen(port, function() {
console.log("Listening on port %s...", port);
});
@zishon89us
Copy link

I created node-cheat:

var express = require('express'),
        fs = require('fs'),
        app = express();
    app.get('/', function (req, res) {
        var filePath = "/files/my_pdf_file.pdf";

        fs.readFile(__dirname + filePath , function (err,data){
            res.contentType("application/pdf");
            res.send(data);
        });
    });

    app.listen(3000, function(){
        console.log('Listening on 3000');
    });

For complete repo:

Clone node-cheat pdf_browser run node app followed by npm install express.

Happy Helping!

@allansli
Copy link

Another example, using express:

var express = require('express');
var path = require('path');

app.get('/downloadFile', function (req, res) {
   var file = path.join(__dirname, 'file.pdf');
   res.download(file, function (err) {
       if (err) {
           console.log("Error");
           console.log(err);
       } else {
           console.log("Success");
       }
   });
});

var server = app.listen(3000, function () {
   console.log('Listening on', server.address().port);
});

@manthankool
Copy link

What you have shown is for the local files stored in the root folder. But what if I want this pdf - https://shodhganga.inflibnet.ac.in/bitstream/10603/75264/8/08_chapter%201.pdf

@Bucephalus-lgtm
Copy link

You can go for implementing download-pdf library in your web app. It will take an url and get it downloaded to your preferred location.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment