Search code examples
javascriptangularjsbase64jpegjspdf

jspdf to addImage : error supplied data is not a JPEG


I am trying to add an image to my pdf:

var image = '../images/example.jpg';
doc.addImage(image, 'JPEG', 0, 0, 700, 145);

and I get this error:

Error: Supplied data is not a JPEG

however, when I add a base64 image:

var image = 'data:image/jpeg;base64,/9j/6GADS...'
doc.addImage(image, 'JPEG', 0, 0, 700, 145);

it works fine!

why is the first version not working? I am trying this:

var image = $base64.encode('../images/example.jpg')

the same error above again!

what is happening here? what is the solution?


Solution

  • You can use this.

    function toDataUrl(src, callback, outputFormat) {
      // Create an Image object
      var img = new Image();
      // Add CORS approval to prevent a tainted canvas
      img.crossOrigin = 'Anonymous';
      img.onload = function() {
        // Create an html canvas element
        var canvas = document.createElement('CANVAS');
        // Create a 2d context
        var ctx = canvas.getContext('2d');
        var dataURL;
        // Resize the canavas to the image dimensions
        canvas.height = this.height;
        canvas.width = this.width;
        // Draw the image to a canvas
        ctx.drawImage(this, 0, 0);
        // Convert the canvas to a data url
        dataURL = canvas.toDataURL(outputFormat);
        // Return the data url via callback
        callback(dataURL);
        // Mark the canvas to be ready for garbage 
        // collection
        canvas = null;
      };
      // Load the image
      img.src = src;
    }