Skip to content

Instantly share code, notes, and snippets.

@zettacristiano
Forked from adamgibbons/node-pdf-generator.js
Created November 15, 2017 10:35
Show Gist options
  • Save zettacristiano/19eab6ef8c4f86fc58c779bd36c863a1 to your computer and use it in GitHub Desktop.
Save zettacristiano/19eab6ef8c4f86fc58c779bd36c863a1 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);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment