javascriptnode.jspdfkitnode-pdfkit

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 

Solution

  • 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();
        }
    });