Skip to content

Instantly share code, notes, and snippets.

@adamgibbons
Last active December 22, 2022 17:38
Show Gist options
  • 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);
});
@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