如何使用NodeJS将PDF缓冲区输出到浏览器? [英] How to output a PDF buffer to browser using NodeJS?

查看:130
本文介绍了如何使用NodeJS将PDF缓冲区输出到浏览器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在使用 html-pdf 转换html,这是我的代码:

So I am using html-pdf to convert my html and here is my code:

var pdf = require('html-pdf')
var html = 'somehtmlfile.html'

pdf.create(html).toBuffer(function (err, buffer) {
        if (err) {
          console.log(err)
        } else {
          console.log(buffer)
          var pdfBuffer = new Buffer(buffer)
          res.setHeader('Content-disposition', 'inline; filename="test.pdf"');
          res.setHeader('Content-type', 'application/pdf');
          res.send(pdfBuffer)
        }
}

在浏览器中,我没有要下载的PDF文件,也​​没有得到pdf文件的输出。 console.log(缓冲区)是这样的:

I am not getting any PDF file to be downloader nor any output of a pdf file in the browser. The console.log(buffer) is this:

<Buffer 25 50 44 46 2d 31 2e 34 0a 31 20 30 20 6f 62 6a 0a 3c 3c 0a 2f 54 69 74 6c 65 20 28 fe ff 29 0a 2f 43 72 65 61 74 6f 72 20 28 fe ff 29 0a 2f 50 72 6f ... >

是否有一种简单的方法?还是我做错了?

Is there a simple way of doing this? Or am I doing it wrong?

我只想在浏览器中以pdf形式输出缓冲区。

I just want to output the buffer in a pdf form in the browser.

推荐答案

更改为:

pdf.create(html).toStream(function(err, stream) {
    if (err) {
        console.log(err)
    } else {
        res.set('Content-type', 'application/pdf');
        stream.pipe(res)
    }
});

这篇关于如何使用NodeJS将PDF缓冲区输出到浏览器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆