我希望使用 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));
});
我想使用其中一种方法 stream 或 buffer 并将其包装在这样的路由处理程序中:
router.get('invoice/pdf', function(req, res) {
res.status(200).send(..pdf data);
});
最佳答案
这在 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)
}
})
})
关于javascript - Node 将 HTML 表达为 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43456488/