Created
November 25, 2016 17:44
-
-
Save DaniJG/fd6596f3b10978e438aba25bfde4275a to your computer and use it in GitHub Desktop.
Node render html as pdf
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
'use strict'; | |
var express = require('express'); | |
var phantom = require('phantom-render-stream'); | |
var readable = require('stream').Readable | |
var app = express(); | |
var router = express.Router(); | |
//For full list of options, see: https://www.npmjs.com/package/phantom-render-stream | |
var renderPdf = phantom({ | |
format : 'pdf', | |
width : 1400, // Changes the width size. Defaults to 1280 | |
height : 900, // Changes the height size. Defaults to 960 | |
paperFormat : 'A4', // Defaults to A4. Also supported: 'A3', 'A4', 'A5', 'Legal', 'Letter', 'Tabloid'. | |
orientation : 'portrait', // Defaults to portrait. 'landscape' is also valid | |
margin : '1cm' // Defaults to 0cm. Supported dimension units are: 'mm', 'cm', 'in', 'px'. No unit means 'px'. | |
}); | |
router.get('/report-url', function(req,res){ | |
//http://stackoverflow.com/questions/11408332/phantomjs-exported-pdf-to-stdout | |
//https://www.npmjs.com/package/phantom-render-stream | |
//http://stackoverflow.com/questions/11598274/display-pdf-in-browser-using-express-js | |
res.contentType("application/pdf"); | |
//Render page at certain url as pdf | |
//Cookies can be set as in: https://www.npmjs.com/package/phantom-render-stream#adding-cookies | |
renderPdf('http://google.com') //It should be able to override default options here, passing them as second argument to renderPdf | |
.pipe(res); | |
}); | |
router.get('/report-string', function(req,res){ | |
res.contentType("application/pdf"); | |
//Build stream with report received as string, http://stackoverflow.com/a/25650163/1836935 | |
// it would also be interesting to accept the request stream? | |
var report = '<!doctype html><html><body><h1>Hello World!</h1></body></html>'; | |
var reportStream = new readable(); | |
reportStream.push(report); | |
reportStream.push(null); | |
//Pipe to the renderPdf function, then to the response | |
reportStream | |
.pipe(renderPdf()) //It should be able to override default options here, passing them as argument to renderPdf | |
.pipe(res); | |
}); | |
app.use('/api', router); | |
var port = process.env.PORT || 9001; | |
app.listen(port); | |
console.log('Listening on port ' + port); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment