Search code examples
javascriptjspdf-autotable

data.cell.textPos shows undefined in jsPDF


I am trying to print a html table which has cells with images, in my pdf using jsPDF:

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]
   },  
})

I get this error when I execute the code:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'x')

When I try to console.log(textPos), I get undefined. Please help me fix this

EDIT: This is my table structure:

This is my table structure


Solution

  • For some reason textPos shows undefined, so I just used data.cell.x and data.cell.y for getting the x and y coordinates.