html2canvas加载图片时的CORS问题

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

我正在使用

html2pdf.js
能够生成网页的PDF文档。

函数看起来像:

html2pdf(someNode, {
  margin: 3,
  filename: 'name.pdf,
  image: { type: 'jpeg', quality: 0.98 },
  html2canvas: {
    scale: 2,
    useCORS: true,
    width: 1300,
    allowTaint: false,
    logging: false,
    proxy: 'https://bucket-name.s3.ap-northeast-1.amazonaws.com' 
  },
  jsPDF: {
    format: 'A4',
    orientation: 'landscape',
    unit: 'mm'
  },
  enableLinks: false
}).then(() => {...})

当我运行

html2pdf
时出现错误:

从来源“https://client.exampledomain.com”访问“https://bucket-name.s3.ap-northeast-1.amazonaws.com/image.jpg”的图像已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。

我的开发类 S3 服务器总是返回

access-control-allow-origin: *
标头,我能够毫无问题地生成 PDF。

但是 S3 仅当我设置

access-control-allow-origin: https://client.exampledomain.com
请求标头时才响应
origin: https://client.exampledomain.com
。但由于某些原因
html2pdf
不添加
Origin
标题。我试图更改
useCORS
allowTaint
proxy
参数但没有运气。

看起来 chrome 正在缓存请求,如果发送的第一个请求没有

crossorigin
标头,那么其他请求将使用与第一个请求 相同的标头发送。并且可以为目标图像设置
crossorigin="anonymous"
。但是我的图像是 CSS 图像:

<div
  style="background-image:https://bucket-name.s3.ap-northeast-1.amazonaws.com/image.jpg"
></div>

我找不到如何为背景图片设置

crossorigin="anonymous"

是否可以手动为确切请求设置

origin
标头或使用javascript清除缓存或者这里可能有任何其他解决方法如何使用
html2canvas
加载跨源图像?

PS 是的,我知道这里有很多关于 html2canvas 和 CORS 错误的问题,但我已经检查了大部分,并且没有任何运气地做了那里提到的所有建议

cors html2canvas
1个回答
0
投票

最后,我放弃了并添加了隐藏的额外图像以能够添加

crossorigin="anonymous"
参数:

<div class="image-to-download"
  style="background-image:https://blahblah.amazonaws.com/image.jpg?placeholder="
><img alt="" style="display:none;" src="https://blahblah.amazonaws.com/image.jpg?withheaders=yes" crossorigin="anonymous">
</div>

并将

placeholder=
查询参数替换为
withheaders=yes
以便能够使用带有 CORS 标头的缓存资源而不是 CORSless 标头:

html2pdf(someNode, {
  ...
  html2canvas: {
    ...
    proxy: 'https://blahblah.amazonaws.com',
    onclone: (doc) => {
      let img;
      // update URLs to load cached cross-originated images
      for (img of doc.getElementsByClassName('image-to-download')) {
        img.style.backgroundImage = img.style.backgroundImage.replace('?placeholder=', '?withheaders=yes');
      }
    }
  },
  jsPDF: {
    ...
  },
  enableLinks: false
}).then(() => {...})
© www.soinside.com 2019 - 2024. All rights reserved.