【问题标题】:Node express HTML to PDFNode express HTML to PDF
【发布时间】:2017-09-13 08:48:17
【问题描述】:

我希望使用 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));
});

我想使用其中一种方法流或缓冲区并将其包装在像这样的路由处理程序中:

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

【问题讨论】:

    标签: html node.js express pdf


    【解决方案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)
        }
      })
    })
    

    【讨论】:

    • 这正是我问我想知道最好的方法的原因,而这正是您指定的。谢谢!
    • 是否需要指定响应为pdf res.setHeader('Content-type', 'application/pdf');
    • Express 应该自动检测文件扩展名,所以 no but ,如果你愿意,你可以明确设置它。如果 Express 检测到您已经通过 res.setHeader() 为响应对象的 headers 提供了一个 Content-Type 标头,那么它将跳过为该标头分配一个值。
    • 您可能需要更正的代码中的轻微错字 pdfStream 在 stream.on 和 stream.pipe 上都被称为流 ;-)
    • @MartinWebb 谢谢,有时直接在答案框中写代码会导致一些错误>.
    猜你喜欢
    • 2017-11-08
    • 2015-07-17
    • 2017-11-23
    • 1970-01-01
    • 2019-03-28
    • 2016-04-19
    • 2013-07-23
    • 2017-12-07
    • 1970-01-01
    相关资源
    最近更新 更多