我正在尝试将 React 组件导出为 PDF 我采取的步骤是
该组件有一些图像,其 URL 是我通过调用其 API 获得的,并且图像的 src 是外部域 url html2canvas 为外部域图像抛出 cors 错误
下面是html中的img元素
这是转换的代码块
html2canvas(containerDiv, { allowTaint: false, useCORS: true, logging: true, }) .then(function (canvas) { const imgData = canvas.toDataURL("image/png"); pdf.addImage(imgData, "PNG", 0, 0, width, height); pdf.save(
${公司名称}.pdf); }) .catch((err) => console.log(err));
已经尝试过的方法:
如果有任何可能的快速解决方法
我建议切换到modern-screenshot,它更轻量级并且提供更好的输出质量,特别是不需要设置代理服务器 - reference。否则,如果您更喜欢坚持使用 html2canvas 解决方案,则需要设置一个代理服务器(这是 lib 作者本人的示例),获取服务器的 URL 并将其用作:
html2canvas(element, {
allowTaint: true,
useCORS: true,
proxy: <server_url>
}).then(canvas => { ... });
希望这有帮助。