Monday, 17 April 2017

Node express HTML to PDF

I'm looking to render a pdf version of a webpage directly to the browser using express. Something like express.render() only render the page as pdf

I have found a module that will convert HTML or a URL to a pdf

https://github.com/marcbachmann/node-html-pdf

What i need to know is how can I use the response from that libary directly in a HTTP route handler to respond to requests with the PDF, I would prefer not to store the PDF, I just want to render it on the fly, and return it as a buffer or a stream to the browser

This is the basic API the module provides:

var pdf = require('html-pdf');
pdf.create(html).toFile([filepath, ]function(err, res){
  console.log(res.filename);
});

pdf.create(html).toStream(function(err, stream){
  stream.pipe(fs.createWriteStream('./foo.pdf'));
});

pdf.create(html).toBuffer(function(err, buffer){
  console.log('This is a buffer:', Buffer.isBuffer(buffer));
});

I want to use one of these methods stream or buffer and wrap it in a route handler like this one:

router.get('invoice/pdf', function(req, res) {
    res.status(200).send(..pdf data);
});



via MartinWebb

No comments:

Post a Comment