Last active
December 22, 2022 17:38
-
-
Save adamgibbons/af2de54c011e68a7b85a to your computer and use it in GitHub Desktop.
Display or download PDF from node.js server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.