Node将HTML表达为PDF

Mar*_*ebb 4 html pdf node.js express

我希望使用express直接将pdf版本的网页呈现给浏览器.像express.render()这样的东西只将页面呈现为pdf

我找到了一个将HTML或URL转换为pdf的模块

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

我需要知道的是如何直接在HTTP路由处理程序中使用来自该库的响应来响应PDF的请求,我宁愿不存储PDF,我只想动态渲染它,然后返回它作为缓冲区或浏览器的流

这是该模块提供的基本API:

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));
});
Run Code Online (Sandbox Code Playgroud)

我想使用这些方法之一流或缓冲区,并将其包装在路由处理程序中,如下所示:

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

pet*_*teb 9

在Node中使用流很容易做到这一点.在a上使用流的主要原因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)
    }
  })
})
Run Code Online (Sandbox Code Playgroud)