使用jsPDF导出带图片HTML表格时data.cell.textPos为undefined的问题
修复jsPDF autoTable导出含图片HTML表格时textPos undefined的问题
我尝试使用jsPDF将包含图片的HTML表格导出为PDF,编写了如下代码:
doc.autoTable({ html: '#news_pos', startX: 10, startY: 20, theme: 'grid', didDrawCell: function(data) { for(var z = 1; z < document.getElementById("news_pos").rows.length; z++){ for(var y = 1; y < document.getElementById("news_pos").rows[z].cells.length; y++){ if(document.getElementById("news_pos").rows[z].cells.item(y).innerHTML.includes("img")){ if (data.column.index === y && data.row.index === z) { var td = data.cell.raw; console.log(td) //shows the correct cell data var img = td.getElementsByTagName('img')[0]; var dim = data.cell.height - data.cell.padding('vertical'); var textPos = data.cell.textPos; doc.addImage(img.src, textPos.x, textPos.y, dim, dim); } } } } }, bodyStyles: {lineColor: [0, 0, 0]}, styles: { fontSize: 10, cellWidth: 'auto', halign: 'center', fillColor: [225, 197, 238] }, })
执行代码时出现错误:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'x')
打印textPos结果为undefined,表格结构如下:
问题原因
textPos是jsPDF-autoTable仅为包含文本的单元格提供的属性,当单元格内只有图片无文本时,该属性会返回undefined。同时嵌套遍历DOM表格的方式效率低,还容易出现索引匹配错误。
修复代码
doc.autoTable({ html: '#news_pos', startX: 10, startY: 20, theme: 'grid', didDrawCell: function(data) { // 仅处理表格体单元格,跳过表头 if (data.section === 'body') { const td = data.cell.raw; const img = td.querySelector('img'); if (img) { // 获取单元格垂直内边距总和 const verticalPadding = data.cell.padding('vertical'); // 计算图片尺寸:单元格高度减去上下内边距 const imgSize = data.cell.height - verticalPadding; // 计算图片起始位置:单元格左上角坐标加上内边距,确保居中 const imgX = data.cell.x + data.cell.padding('horizontal'); const imgY = data.cell.y + verticalPadding / 2; // 添加图片到PDF doc.addImage(img.src, imgX, imgY, imgSize, imgSize); } } }, bodyStyles: {lineColor: [0, 0, 0]}, styles: { fontSize: 10, cellWidth: 'auto', halign: 'center', fillColor: [225, 197, 238] }, })
关键修改说明
- 移除冗余的DOM遍历逻辑,直接通过
data.cell.raw获取当前绘制的单元格DOM元素,用querySelector快速定位图片 - 用单元格自身的坐标属性
data.cell.x、data.cell.y替代textPos,这两个属性始终存在,不受单元格内容影响 - 增加
data.section === 'body'判断,避免处理表头单元格 - 优化图片位置计算,结合单元格内边距确保图片在单元格内居中显示
内容的提问来源于stack exchange,提问作者user19835820
相关产品推荐
相关产品推荐

