Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output a PDF buffer to browser using NodeJS?

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)
        }
}

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?

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

like image 784
wobsoriano Avatar asked Mar 29 '17 15:03

wobsoriano


3 Answers

Change to:

pdf.create(html).toStream(function(err, stream) {
    if (err) {
        console.log(err)
    } else {
        res.set('Content-type', 'application/pdf');
        stream.pipe(res)
    }
});
like image 171
Diego ZoracKy Avatar answered Nov 11 '22 04:11

Diego ZoracKy


you can use the below function or html.create(somehtmlfile.html).toStream()

function to convert a buffer to stream

 function bufferToStream(buffer) {  
     let stream = new Duplex();
     stream.push(buffer);
     stream.push(null);
     return stream;
   }

download or view a pdf in browser if it's a stream

var pdf = require('html-pdf')
var html = 'somehtmlfile.html'
exports.generatePdf = (req, res) =>{
    pdf.create(html).toBuffer(function (err, buffer) {
            if (err) {
              console.log(err)
            } else {
              console.log(buffer)

           bufferToStream(buffer).pipe(res)
            }
    }
}
like image 22
muthukumar selvaraj Avatar answered Nov 11 '22 03:11

muthukumar selvaraj


pdf.create(html).toBuffer(function (err, buffer) {
    if (err) {
        console.log(err)
    } else {
        console.log(buffer)
        res.header('Content-type', 'application/pdf')
        res.send(buffer)
    }
}
like image 1
gurrala harikrishna Avatar answered Nov 11 '22 05:11

gurrala harikrishna