Nate Poynter Nate Poynter - 1 month ago 29
Javascript Question

Converting images to base64 within a loop before adding to jspdf - javascript

I have researched issues with the base64 conversion and jspdf function quite a bit. ( PS this is my first question on stackoverflow, please bare with any rookie mistakes ).

All seems to work fine with the below code except that the pdf is generated and saved before the loop where the images are converted to base64 and placed to the document is finished. I added a couple alerts to check timing. Would the solution be to check when the loop is finished, the images placed before continuing with the pdf function? if so, how? please help.

$(document).ready(function(){
$("a#getdoc").click(function(){
var doc = new jsPDF('landscape, in, legal');
var myimages = 'img1.jpg|img2.jpg|img3.png';
var myimgarray = myimages.split('|');

function convertImgToBase64(url, callback, outputFormat){
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
return canvas.toDataURL("image/jpeg");
var dataURL = canvas.toDataURL("image/jpeg");
callback(dataURL);
canvas = null;
}

for(var i = 0; i < myimgarray.length; i++)
{
icount.count = i;
var img = new Image();
alert(checkoutimgarray);

img.src = '/Portals/0/repair-images/' + myimgarray[i];
img.onload = function(){
newData = convertImgToBase64(img);
alert(newData);
doc.addImage(newData, 'JPEG', (icount * 100), 10, 70, 15); // would doc be undefined here? out of scope?
};
}

doc.setFontSize(20);
doc.text(100, 20, "This is a test to see if images will show");
doc.save('My_file.pdf');

});
});

Answer
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");

function convertImgToBase64(img, outputFormat){

    // clear canvas
    canvas.width = img.width;
    canvas.height = img.height;

    // draw image
    ctx.drawImage(img, 0, 0);

    // get data url of output format or defaults to jpeg if not set
    return canvas.toDataURL("image/" + (outputFormat || "jpeg"));
}

var images = [];

for(var i = 0; i < myimgarray.length; i++) {        
      var img = new Image();
      img.onload = function() {
          images.push({
              base64: convertImgToBase64(this),
              width: this.width,
              height: this.height
          });

          // all images loaded
          if(images.length === myimgarray.length) {
              for(var j = 0; j < images.length; j++) {             
                  doc.addImage(images[j].base64, 'JPEG', (j * 100), 10, 70, 15);
              }    
              doc.setFontSize(20);
              doc.text(100, 20, "This is a test to see if images will show");
              doc.save('My_file.pdf');
          }
      };
      img.src = '/Portals/0/repair-images/' + myimgarray[i];
}