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

使用jsPDF与html2canvas调用addHTML方法时遭遇报错的技术咨询

解决jsPDF + html2canvas生成PDF时addHTML报错的问题

我帮你梳理下问题所在,以及对应的修复方案,都是实际开发中踩过的坑:

1. 核心问题:弃用的addHTML方法

jsPDF的addHTML早就被官方标记为弃用了,新版本的库已经不再维护这个方法,这是你报错的最主要原因。现在推荐两种更可靠的方案:要么用html2canvas生成canvas后通过addImage添加到PDF,要么直接使用jsPDF内置的html()方法。

2. 次要问题:html2canvas参数传错了

你的代码里写的是html2canvas($('#information').html()),这里传入的是HTML字符串,但html2canvas需要的是DOM元素对象,不是字符串。得改成传入jQuery对应的DOM节点:

html2canvas($('#information')[0]) 
// 或者用原生写法 document.getElementById('information')

修复后的完整函数示例

下面是调整后的代码,既解决了弃用方法的问题,也修正了参数错误,还保留了分页和文件名逻辑:

function imprimirPDF() { 
  // 建议指定PDF的尺寸和单位,避免排版混乱
  var pdf = new jsPDF('p', 'mm', 'a4'); 
  var targetElement = document.getElementById('information');
  
  html2canvas(targetElement, {
    scale: 2, // 提升生成图片的清晰度,替代原代码里的retina参数
    useCORS: true // 如果页面里有跨域图片,必须开启这个选项
  }).then(function (canvas) {
    // 将canvas转换成图片数据
    var imgData = canvas.toDataURL('image/png');
    var imgWidth = 210; // A4纸的宽度(单位:mm)
    var pageHeight = 297; // A4纸的高度(单位:mm)
    var imgHeight = canvas.height * imgWidth / canvas.width;
    var remainingHeight = imgHeight;
    var currentPosition = 0;

    // 添加第一页内容
    pdf.addImage(imgData, 'PNG', 0, currentPosition, imgWidth, imgHeight);
    remainingHeight -= pageHeight;

    // 自动处理分页(替代原代码里的pagesplit参数)
    while (remainingHeight >= 0) {
      currentPosition = remainingHeight - imgHeight;
      pdf.addPage();
      pdf.addImage(imgData, 'PNG', 0, currentPosition, imgWidth, imgHeight);
      remainingHeight -= pageHeight;
    }

    // 生成最终文件名
    var fileName = 'Informe ' + $('#reportType option:selected').text() + ' ' + $('#curso option:selected').text(); 
    if ($scope.filterAlumni != null) fileName += ' ' + $('#filterAlumni option:selected').text(); 
    pdf.save(fileName + '.pdf');
  }).catch(function(error) {
    // 捕获错误方便调试
    console.error('生成PDF时出错:', error);
  });
}

更简洁的替代方案:用jsPDF内置的html()方法

如果你不想手动处理分页,也可以直接用jsPDF的内置html()方法,它已经集成了html2canvas的能力:

function imprimirPDF() {
  var pdf = new jsPDF('p', 'mm', 'a4');
  var targetElement = document.getElementById('information');
  
  pdf.html(targetElement, {
    callback: function(generatedPdf) {
      var fileName = 'Informe ' + $('#reportType option:selected').text() + ' ' + $('#curso option:selected').text(); 
      if ($scope.filterAlumni != null) fileName += ' ' + $('#filterAlumni option:selected').text(); 
      generatedPdf.save(fileName + '.pdf');
    },
    x: 0,
    y: 0,
    width: 210 // 匹配A4纸宽度
  });
}

额外注意点

  • 确保你用的是最新版本的jsPDF和html2canvas,旧版本兼容性问题很多
  • 如果页面里有动态加载的内容,要确保在调用生成PDF函数前,内容已经渲染完成
  • 若页面包含跨域图片,除了开启useCORS,还要确保图片服务器配置了CORS允许你的域名访问

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:49:04