How to write images from URL to PDFkit?

15.1k views Asked by At

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 
3

There are 3 answers

0
dimacpp On BEST ANSWER

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();
    }
});
1
vxn On

TypeScript and node-fetch example:

const fetchImage = async (src: string) => {
  const response = await fetch(src);
  const image = await response.buffer();

  return image;
};
    
const logo = await fetchImage("https://i.imgur.com/2ff9bM7.png");
doc.image(logo, 0, 200);
0
Elia Weiss On

JS and Axios example:

async function fetchImage(src) {
    const image = await axios
        .get(src, {
            responseType: 'arraybuffer'
        })
    return image.data;
}

const logo = await fetchImage("https://i.imgur.com/2ff9bM7.png");
doc.image(logo, 0, 200);