Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write images from URL to PDFkit?

I am getting a JPEG from a URL using node.js requests. I then convert the image to a base64 buffer and write it to the pdf document:

request({ url: url, encoding: null }, function (error, response, body) {
                        if (!error && response.statusCode == 200) {
                            var img = new Buffer(body, 'base64');
                            pdf.image(img, 0, 0);
                            callback(error, body);
                        }
                    });

I am getting the following error message:

events.js:160
      throw er; // Unhandled 'error' event
      ^

Error: stream.push() after EOF
    at readableAddChunk (_stream_readable.js:156:17)
    at PDFDocument.Readable.push (_stream_readable.js:134:10)
    at PDFDocument._write (/Users/assafshamia/Freebird/node/utils/report_generator/node_modules/pdfkit/js/document.js:156:12)
    at PDFReference.finalize (/Users/assafshamia/Freebird/node/utils/report_generator/node_modules/pdfkit/js/reference.js:81:21)
    at PDFReference.finalize (/Users/assafshamia/Freebird/node/utils/report_generator/node_modules/pdfkit/js/reference.js:10:59)
    at PDFReference.end (/Users/assafshamia/Freebird/node/utils/report_generator/node_modules/pdfkit/js/reference.js:74:21)
    at JPEG.embed (/Users/assafshamia/Freebird/node/utils/report_generator/node_modules/pdfkit/js/image/jpeg.js:68:16)
    at PDFDocument.image (/Users/assafshamia/Freebird/node/utils/report_generator/node_modules/pdfkit/js/mixins/images.js:34:15)
    at addImage (/Users/assafshamia/Freebird/node/utils/report_generator/dist/all.js:19:6)
like image 580
NightOwl Avatar asked Sep 14 '17 15:09

NightOwl


1 Answers

Your code looks fine for me.
However, here is 100% working snippet:

request({ url, encoding: null }, (error, response, body) => {

    if (!error && response.statusCode === 200) {
        pdf.pipe(fs.createWriteStream('out.pdf'));

        var img = new Buffer(body, 'base64');
        pdf.image(img, 0, 0);

        pdf.end();
    }
});
like image 55
dimacpp Avatar answered Oct 05 '22 02:10

dimacpp