节点将HTML表示为PDF

我正在寻找使用快递直接向浏览器呈现网页的pdf版本。 像express.render()这样的东西只会将页面渲染为pdf

我find了一个将HTML或URL转换为PDF的模块

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

我需要知道的是,如何直接在HTTP路由处理程序中使用该库的响应来响应使用PDF的请求,我不想存储PDF,我只是想dynamic呈现它,并返回它作为浏览器的缓冲区或stream

这是模块提供的基本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)); }); 

我想使用这些方法之一stream或缓冲区,并将其包装在这样一个路由处理程序:

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

在Node中使用stream很容易。 在Buffer上使用stream的主要原因是stream不需要像Buffer那样将所有数据保存在内存中。 相反,它可以根据需要向读者或作者提供数据。 这意味着它是轻量级的,在延迟和吞吐量方面性能会更好。

在你的情况下,你只是想将stream的内容直接传递给你的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) } }) })