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

html2canvas配合jsPDF导出PDF报createObjectURL is not a function错误

问题解决方法

以下是针对该报错的可落地修复方案:

1. 修复canvas转DataURL的语法错误

你当前canvas.toDataURL的传参写法错误,MIME类型和质量参数需要分开传递,不能合并在同一个引号内:
错误写法:

var imgData = canvas.toDataURL('image/jpeg, 1.0');

修正后的写法:

var imgData = canvas.toDataURL('image/jpeg', 1.0);

该错误会导致生成的图片DataURL格式异常,jsPDF处理无效资源时就会触发createObjectURL调用失败的报错。

2. 补全createObjectURL的兼容逻辑

jsPDF 1.5.3版本对部分新浏览器环境的API适配存在缺陷,可在调用pdf.save前手动添加兜底兼容:

// 放在downloadPDF函数开头即可
if (typeof window.URL.createObjectURL === 'undefined') {
  window.URL.createObjectURL = window.URL.createObjectURL || window.webkitURL.createObjectURL || window.mozURL.createObjectURL || window.msURL.createObjectURL;
}

3. 修复隐藏元素绘制异常问题

Bootstrap模态框未打开时#printItems元素处于隐藏状态,html2canvas绘制隐藏元素会生成无效canvas,间接导致后续jsPDF处理失败,可修改代码临时显示元素完成绘制后再恢复状态:

function downloadPDF() {
  const printDom = $("#printItems")[0];
  // 临时显示待绘制元素
  const originStyle = printDom.style.cssText;
  printDom.style.display = 'block';
  printDom.style.opacity = '0';
  printDom.style.position = 'fixed';
  printDom.style.top = '-10000px';

  html2canvas(printDom, {
    allowTaint: true,
    useCORS: true, // 处理跨域图片资源
    scale: 2 // 提升导出PDF清晰度
  }).then(function(canvas) {
    // 恢复元素原有样式
    printDom.style.cssText = originStyle;
    
    var imgData = canvas.toDataURL('image/jpeg', 1.0);
    var pdf = jsPDF({
      unit: 'mm',
      format: 'a4',
      orientation: 'portrait'
    });
    // 适配A4纸尺寸,避免内容溢出
    const imgWidth = 180;
    const imgHeight = canvas.height * imgWidth / canvas.width;
    pdf.addImage(imgData, 'jpeg', 15, 10, imgWidth, imgHeight);
    pdf.save('test.pdf');
  });
}

4. 校验依赖加载状态

确保依赖加载顺序正确:先加载html2canvas,再加载jsPDF,禁止在依赖未加载完成时触发downloadPDF函数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:36:05