How to write images from URL to PDFkit?
Asked Answered
D

3

8

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 
Donothing answered 14/9, 2017 at 15:18 Comment(1)
Could it be that pdf.end() is getting called prematurely?Jenicejeniece
A
5

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();
    }
});
Avrom answered 23/9, 2017 at 7:7 Comment(0)
A
10

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);
Authority answered 9/6, 2021 at 6:25 Comment(0)
A
5

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();
    }
});
Avrom answered 23/9, 2017 at 7:7 Comment(0)
A
3

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);
Afferent answered 7/9, 2020 at 8:26 Comment(1)
Please note that response.buffer() does not exist. It's called response.arrayBuffer()Indigo

© 2022 - 2024 — McMap. All rights reserved.