How to achieve nested tables in a PDF using jspdf and jspadf-autotable? Something similar to the picture below:
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
There is no native support for having nested tables in jspdf-autotable. And doing it with the hooks becomes quite messy because of a current bug where you can't use graphic functions in the hooks. Here is a workaround that records the positions that the nested tables in the drawCell hook and then paints the secondary tables over the original one in a loop afterwards.
var elem = document.getElementById("generate");
elem.onclick = function() {
var doc = new jsPDF('p', 'pt');
var elem = document.getElementById('table');
var data = doc.autoTableHtmlToJson(elem);
var positions = [];
doc.autoTable(data.columns, data.rows, {
drawCell: function(cell, data) {
if (data.column.dataKey === 5) {
positions.push({x: cell.x, y: cell.y + 5});
}
},
columnStyles: {
5: {columnWidth: 120}
},
bodyStyles: {
rowHeight: 100
}
});
positions.forEach(function(pos) {
var rows = [
["1", "2", "3", "4"],
["1", "2", "3", "4"],
["1", "2", "3", "4"],
["1", "2", "3", "4"]
];
doc.autoTable(["One", "Two", "Three", "Four"], rows, {
startY: pos.y,
margin: {left: pos.x},
tableWidth: 'wrap',
theme: 'grid',
styles: {
cellPadding: 3,
fontSize: 9,
rowHeight: 15
}
});
});
doc.save("table.pdf");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.debug.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/2.0.33/jspdf.plugin.autotable.js"></script>
<button id="generate">Generate PDF</button>
<table id="table" style="display: none;">
<thead>
<tr>
<th>ID</th>
<th>First name</th>
<th>Last name</th>
<th>Email</th>
<th>Country</th>
<th>Table</th>
</tr>
</thead>
<tbody>
<tr>
<td align="right">1</td>
<td>Donna</td>
<td>Moore</td>
<td>dmoore0@furl.net</td>
<td>China</td>
<td></td>
</tr>
<tr>
<td align="right">2</td>
<td>Janice</td>
<td>Henry</td>
<td>jhenry1@theatlantic.com</td>
<td>Ukraine</td>
<td></td>
</tr>
<tr>
<td align="right">3</td>
<td>Ruth</td>
<td>Wells</td>
<td>rwells2@constantcontact.com</td>
<td>Trinidad and Tobago</td>
<td></td>
</tr>
<tr>
<td align="right">4</td>
<td>Jason</td>
<td>Ray</td>
<td>jray3@psu.edu</td>
<td>Brazil</td>
<td></td>
</tr>
<tr>
<td align="right">5</td>
<td>Jane</td>
<td>Stephens</td>
<td>jstephens4@go.com</td>
<td>United States</td>
<td></td>
</tr>
<tr>
<td align="right">6</td>
<td>Adam</td>
<td>Nichols</td>
<td>anichols5@com.com</td>
<td>Canada</td>
<td></td>
</tr>
</tbody>
</table>