Node将HTML表达为PDF

Node将HTML表达为PDF,第1张

概述我希望使用express直接将pdf版本的网页呈现给浏览器.像express.render()这样的东西只将页面呈现为pdf 我找到了一个将HTML或URL转换为pdf的模块 https://github.com/marcbachmann/node-html-pdf 我需要知道的是如何直接在HTTP路由处理程序中使用来自该库的响应来响应PDF的请求,我宁愿不存储PDF,我只想动态渲染它,然后返回它 我希望使用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);});
解决方法 在Node中使用流很容易做到这一点.在Buffer上使用流的主要原因是流不需要像Buffer一样将所有数据保存在内存中.相反,它可以根据需要向读者或作者提供数据.这意味着它是轻量级的,并且在延迟和吞吐量方面性能更好.

在您的情况下,您只想将流的内容直接传递给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)    }  })})
总结

以上是内存溢出为你收集整理的Node将HTML表达为PDF全部内容,希望文章能够帮你解决Node将HTML表达为PDF所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1083297.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存