Node express HTML to PDF

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

I found a module that converts HTML or URL to pdf

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

I need to know how I can use the response from this library directly in the HTTP route handler to respond to requests using PDF, I would prefer not to store the PDF file, I just want to display it on the fly, and return it to the buffer or stream to the browser

This is the basic API that 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 a stream or buffer and wrap it in a route handler similar to this:

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

Node, . Buffer , , Buffer. . , .

pipe() res.

router.get('/invoice/pdf', (req, res) => {
  pdf.create(html).toStream((err, pdfStream) => {
    if (err) {   
      // handle error and return a error response code
      console.log(err)
      return res.sendStatus(500)
    } else {
      // send a status code of 200 OK
      res.statusCode = 200             

      // once we are done reading end the response
      pdfStream.on('end', () => {
        // done reading
        return res.end()
      })

      // pipe the contents of the PDF directly to the response
      pdfStream.pipe(res)
    }
  })
})
+5

Source: https://habr.com/ru/post/1674988/


All Articles