在Angular 8的jsPDF中从另一个域添加图像的CORS错误

问题描述 投票:0回答:1

我想在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 ='Anonymous';

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

CORS_ORIGIN_ALLOW_ALL = True
angular jspdf
1个回答
0
投票

为澄清起见,我创建了一个codesandbox

我通常将我的图像添加为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);

您完成了。

© www.soinside.com 2019 - 2024. All rights reserved.