使用jspdf将图像添加到PDF会使图像变黑

时间:2014-12-18 06:33:16

标签: javascript image pdf-generation jspdf

当我尝试将URL中的图像添加到PDF文件时,图像会显示为黑色    但是,当我再次单击下载pdf按钮时,图像将添加到PDF中。仅限   当我第一次这样做时,图像变成黑色。

 function getBase64Image(url) {

alert(url);
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var img = new Image();
img.src = url;
img.style.height ="181px";
img.style.width ="183px";
//img.crossOrigin ="Anonymous";

context.drawImage(img,0,0);

var dataURL = canvas.toDataURL("image/jpeg");
alert(dataURL);
document.body.appendChild(img);


var doc = new jsPDF('landscape');

doc.addImage(img,'JPEG',0,0,50,50);
doc.save('Saved.pdf');

 }

getBase64Image("http://localhost:64931/jspdf/download.png");

1 个答案:

答案 0 :(得分:1)

当您更改代码时会发生什么:

将JPEG更改为PNG,这对我有用。

function getBase64Image(url) {

alert(url);
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var img = new Image();
img.src = url;
img.style.height ="181px";
img.style.width ="183px";
//img.crossOrigin ="Anonymous";

context.drawImage(img,0,0);

var dataURL = canvas.toDataURL("image/png");
alert(dataURL);
document.body.appendChild(img);


var doc = new jsPDF('landscape');

doc.addImage(img,'PNG',0,0,50,50);
doc.save('Saved.pdf');

 }

getBase64Image("http://localhost:64931/jspdf/download.png");