NodeJS Express PdfKit image issue

122 Views Asked by At

Hey all the issue i am having is I have an array of image urls and what i am trying to do is loop the images and add the image to the pdfkit document.

the urls of the images are valid and it works fine if i dont have it in a loop and not doing request get to get the buffer and just hardcode the buffer to a string but i need it to work in the array.

it just results in the pdf being blank if using it inside of the array loop.

    const doc = new PDFDocument({ size: 'A6' });
    var finalString = ''; // contains the base64 string
    var stream = doc.pipe(new Base64Encode());

    for (i = 0; i < labels.length; i++) {
    console.log(`attemping to add image ${labels[i]}`);

    await request.get({
    "uri": `${labels[i]}`,
    "encoding": null
    }, function(err, response, body){ 
    data = "data:" + response.headers["content-type"] + ";base64," + Buffer.from(body).toString('base64');
    // Remove header
    data = data.split(';base64,').pop();
    //console.log(data);
    const img = Buffer.from(data, 'base64');
    //console.log(img);
    doc.image(img, 5, 5, {fit: [300, 400], align: 'center', valign: 'center'})
    .rect(430, 15, 100, 100).stroke()
    .text('Centered', 430, 0);
    });
}
  doc.end()
  
  stream.on('data', function(chunk) {
  finalString += chunk;
  });
  
  stream.on('end', function() {
  return res.json(finalString);
  });
0

There are 0 best solutions below