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

新版jsPDF转换HTML表格为PDF时提示未定义的解决方法

问题分析

出现jsPDF not defined错误及原有代码失效的核心原因:

  1. 新版jsPDF已移除旧版的fromHTML方法,改用html()方法实现HTML转PDF
  2. 新版UMD格式的jsPDF不再直接暴露全局jsPDF变量,需从window.jspdf对象中获取
  3. 新版html()方法依赖html2canvas库完成HTML渲染

解决方案

1. 正确引入依赖库

确保按顺序引入以下库(替换你当前的引入链接):

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

2. 适配新版API的JS代码

替换原有JS代码,使用新版html()方法:

$('.cmd').click(function () {  
  // 从全局对象中获取jsPDF类
  const { jsPDF } = window.jspdf;
  // 初始化PDF实例(参数:方向、单位、纸张尺寸)
  const pdf = new jsPDF('p', 'mm', 'a4');
  
  // 获取需要转换的表格元素(根据你的HTML结构调整)
  const targetTable = $(this).closest('.content').find('table')[0];
  
  // 使用新版html方法生成PDF
  pdf.html(targetTable, {
    x: 15, // 内容起始X坐标
    y: 15, // 内容起始Y坐标
    width: 170, // 内容宽度
    callback: function(generatedPdf) {
      generatedPdf.save('sample-file.pdf');
    }
  });
});

补充说明

  • 若你确实需要使用.content-template模板元素,只需将targetTable替换为该模板的DOM对象即可
  • 如需处理特殊元素(如跳过某些节点),可在html()方法的配置项中添加html2canvas的相关参数
  • 确保所有依赖库加载顺序正确:jQuery → html2canvas → jsPDF

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 16:52:49