gael
gael

Reputation: 55

jsPDF and image loading

I'm tryna use the jsPDF library. I'd like to load and insert an image, and export the PDF file.

My issue is about the image loading. I'm doing this: var imageData = getBase64Image('thinking-monkey.jpg'); and I should get the dataURL in base64 inside imageData.

My getBase64Image() function does the following:

function getBase64Image(url) {
    var img = new Image();
    var dataURL;

    img.src = url;

    img.onload = function() {
        var canvas = document.createElement('canvas');
        canvas.width = img.width;
        canvas.height = img.height;

        var context = canvas.getContext('2d');
        context.drawImage(img, 0, 0);

        dataURL = canvas.toDataURL('image/jpeg');

    }

    return dataURL;
}

But it returns 'undefined', because the image is like 65 Kb and doesn't load up at once. So when at return dataURL; the variable is still undefined.

I've tried to add a setTimeout() right before return dataURL; but it doesn't seem to be working.

How can I wait until the image is fully loaded to return dataURL?

Thanks.

Upvotes: 0

Views: 13034

Answers (2)

TheRealPapa
TheRealPapa

Reputation: 4539

Move the "return" statement inside the img.onload function, this should do it I suspect.

function getBase64Image(url) {
    var img = new Image();
    var dataURL;

    img.src = url;

    img.onload = function() {
        var canvas = document.createElement('canvas');
        canvas.width = img.width;
        canvas.height = img.height;

        var context = canvas.getContext('2d');
        context.drawImage(img, 0, 0);

        dataURL = canvas.toDataURL('image/jpeg');

        return dataURL;   /* MOVED */
    }
}

Upvotes: 0

rowasc
rowasc

Reputation: 320

You can use a callback. Pass the code that you want to execute after the image is fully loaded to the getBase64Image function, and execute it in the .onLoad function.

it would be something like this. (generatePdf is a function)

function getBase64Image(url,generatePdf) {
    var img = new Image();
    var dataURL;

    img.src = url;

    img.onload = function() {
        var canvas = document.createElement('canvas');
        canvas.width = img.width;
        canvas.height = img.height;

        var context = canvas.getContext('2d');
        context.drawImage(img, 0, 0);

        dataURL = canvas.toDataURL('image/jpeg');
        generatePdf(dataUrl);
    }
}
var generatePdf= function generatePdf(imageData){
   /** this function receives the image param and creates the pdf with it**/
   var doc = new jsPDF();
   doc.addImage(imageData, "JPEG", 60,50); 
   doc.save("test.pdf");
};

function generateImagePdf(url){ 
    getBase64Image(url, generatePdf);
}
//now call the generateImagePdf function, which will call the generateBase64Image function and wait for tyhe image to load to call the generatePdf function with the param
generateImagePdf("imageurl.jpg") ;

Upvotes: 2

Related Questions