You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用html2pdf导出PDF时无法加载chart.googleapis.com二维码如何解决

问题原因

html2pdf 底层依赖 html2canvas 实现页面内容截图,二维码空白是以下几个常见原因导致:

  • 配置项重复:你定义的 opt 对象中出现了两次html2canvas字段,后者会直接覆盖前者的scale、dpi等生效配置
  • 跨域资源限制:chart.googleapis.com 的图片属于跨域资源,html2canvas 默认不加载跨域图片避免画布污染
  • 图片响应头限制:谷歌图表接口的响应头未配置允许跨域标识,即使开启跨域配置也可能加载失败
修复方案

1. 补全img标签属性

给二维码img标签添加crossorigin="anonymous"属性,示例:

<img src="https://chart.googleapis.com/chart?chs=250x250&cht=qr&chl=http://hellovcard.com/6160175f9b7f3&choe=UTF-8&chof=gif" alt="qr code" crossorigin="anonymous">

2. 修正导出配置,开启跨域加载

合并重复的html2canvas配置,添加跨域加载相关参数:

function saveAsPDF() {
    var element = document.getElementById('printableArea');
    var opt = {
        margin: 0.3,
        filename: 'download.pdf',
        image: {type: 'jpeg', quality: 1},
        html2canvas: {
            scale: 4, 
            dpi: 72, 
            letterRendering: true,
            useCORS: true, // 允许加载跨域图片
            allowTaint: false, // 不允许跨域图片污染画布
            onclone: (element) => {
                const svgElements = Array.from(element.querySelectorAll('svg'));
                svgElements.forEach(s => {
                    const bBox = s.getBBox();
                    s.setAttribute("x", bBox.x);
                    s.setAttribute("y", bBox.y);
                    s.setAttribute("width", bBox.width);
                    s.setAttribute("height", bBox.height);
                })
            }
        },
        jsPDF: {unit: 'in', format: 'A2'}
    };
    html2pdf().set(opt).from(element).save();
}

3. 兜底方案:预转图片为base64

如果上述方案仍不生效,可提前将二维码图片转为base64格式后再插入页面,完全规避跨域问题,示例代码:

// 提前调用该方法将二维码转为base64,替换原有img的src
function getQrBase64(url, callback) {
    const img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function() {
        const canvas = document.createElement('canvas');
        canvas.width = img.width;
        canvas.height = img.height;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0);
        callback(canvas.toDataURL('image/png'));
    };
    img.src = url;
}

内容的提问来源于stack exchange,提问作者kumari shwetha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 17:36:01