Search code examples
javascriptjquerypdfpdf-generationpdfmake

"Uncaught TypeError: Cannot read property 'embed' of undefined" when using custom image in the pdfMake pdf engine


I am trying to download some reports in my application as pdf using pdfMake pdf engine and I adding a jpg logo image as,

var logoImg = 'sampleImage.jpg';
var logoImage = "http://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg";
if (logoImage) {
     var img = new Image();
     img.setAttribute('crossOrigin', 'anonymous');
     img.src = logoImage;
     var canvas = document.createElement("canvas");
     canvas.width = img.width;
     canvas.height = img.width;
     var ctx = canvas.getContext("2d");
     ctx.drawImage(img, 0, 0);
     logoImg = canvas.toDataURL("image/png");
 }

which is given in this fiddle. But when I using a custom image, it gives Uncaught TypeError: Cannot read property 'embed' of undefined error when clicking the download button at the first time (check the console). When I run the ode once again, then the pdf will download correctly. So how can I solve the Uncaught TypeError error?

Edit: It will work correctly if I give the dataurl of image directly as given in this fiddle. But I want to pass dataurl dynamically based on image link as given in the first fiddle above.


Solution

  • I could resolve the "Uncaught TypeError: Cannot read property 'embed' of undefined" by providing the image in Base64.

    I found the solution here.

    For more information about PDFMake and Images, here's the documentation.