在Angular 8中的jsPDF中添加来自另一个域的图像时出现CORS错误



我想在jsPdf中使用一些图像。这些图像来自另一个域(API(。这是我的代码:

let img = new Image();
img.src = 'myUrl';
docPdf.addImage(img, 'JPEG', col, row, width, height, 'FAST');

但我收到这个错误:

Access to image at 'http://127.0.0.1:8000/some-url' from origin 'http://127.0.0.1:4000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
ERROR Error: Supplied Data is not a valid base64-String jsPDF.convertStringToImageData 
at Object.x.convertStringToImageData (jspdf.min.js:50)

然后我把crossOrigin添加到我的url中,但我也收到了那个错误。

img.crossOrigin = 'anonymous';

或img.crossOrigin="匿名";

我还在后台设置了cors设置:

CORS_ORIGIN_ALLOW_ALL = True

如果您的后端已经接受所有来源,并且您正在设置img.crossOrigin = 'anonymous',您可以尝试在图像URL中添加一个随机参数:

img.src = imgUrl + '?r=' + Math.floor(Math.random()*100000);

看起来浏览器已经缓存了您的图像,但它不会让任何javascript从磁盘读取图像。在imageURL中添加一个随机参数,它将错过浏览器缓存的图像,并从服务器上再次下载。

为了澄清,我创建了一个代码沙盒。

我通常将我的图像添加为base64编码的数据URL。如果图片来自不同的域(比如当你在数据库中存储图片链接时(,我用以下方法将图片转换到baset64客户端:

toDataURL(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
};
reader.readAsDataURL(xhr.response);
};
xhr.open("GET", url);
xhr.responseType = "blob";
xhr.send();
},

created()方法中(或者当您需要将图像转换为base64时(,您可以设置在数据obj:中声明的url属性

created() {
this.toDataURL(this.imgUrl, data => {
this.imgAsBase64 = data;
});
}

然后简单地添加图像:

doc.addImage(this.imgAsBase64, "jpg", 10, 10);

你完成了。

最新更新