Nested Table In Jspdf
I am developing a table using jspdf. I try to put autotable in autotable. The problem is that the row of the table is not dynamically adjusted to the height of the inserted table.
Solution 1:
Before you create the nested table you must set the minimal height of the parent cell in the didParseCell event and clear the content. And add the nested table as extra content in the didDrawCell event.
This is an example with an HTML table and nested table in one cell. The height calculated is using the assumption that the rows are all equal height. (typescript)
...
this.yPos = 0;
this.createAutoTable(myTableNode, { startY: this.yPos + 20 })
...
/**
* create the autotable with the plugin
*/
private createAutoTable(tableNode, tableStyle = {}): void {
this.autoTable(this.doc, {
...tableStyle,
html: tableNode,
// event that can be used to override content or styles for a specific celldidParseCell: data => {
const rawNode = data.cell.rawasHTMLTableCellElement;
const nestedTable = rawNode.querySelector('table');
if (nestedTable) {
this.prepareCellForNestedTable(data.cell, nestedTable);
}
},
// event to add additional cell contentdidDrawCell: data => {
const rawNode = data.cell.rawasHTMLTableCellElement;
const nestedTable = rawNode.querySelector('table');
// if there is a nested table draw that tableif (nestedTable) {
const subTableStyle = {
html: nestedTable,
startY: data.cell.y + 4,
margin: { left: data.cell.x + 4 },
tableWidth: data.cell.width - 4
};
this.createAutoTable(nestedTable, subTableStyle)
}
});
// @ts-ignorethis.yPos = this.doc.lastAutoTable.finalY + 10;
}
/**
* if there is a nested table inside a cell then clear the content and set the height of the cell
*/
private prepareCellForNestedTable(cell, nestedTable: HTMLTableElement) {
cell.styles.minCellHeight = this.getTotalRows(nestedTable) * 11; // calc how many rows are needed?
cell.text = [];
}
/**
* Count total rows of nested table for calculating the height of primary table (assumption 1 row height cells)
*/
private getTotalRows(table): number {
return table.querySelectorAll('tr').length;
}
Post a Comment for "Nested Table In Jspdf"