jspdf to addImage:错误提供的数据不是JPEG

时间:2017-06-11 18:54:23

标签: javascript angularjs base64 jpeg jspdf

我正在尝试将图像添加到我的pdf中:

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

我收到此错误:

  

错误:提供的数据不是JPEG

但是,当我添加base64图像时:

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

它工作正常!

为什么第一个版本不起作用? 我正在尝试这个:

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

再次出现同样的错误!

这里发生了什么?解决方案是什么?

1 个答案:

答案 0 :(得分:2)

您可以使用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;
}