I'm trying to build a small app with jspdf and jspdf-Autotable but I don't find how to create a custom last row with another variable value in an existing table.
What I just have done so far is this:
doc.autoTable({
body: concepts,
columns: [{ header: 'Concept', dataKey: 'name' }, { header: 'Amount', dataKey: 'amount' }],
didDrawPage: function (data) {
let rows = data.table.body;
rows.push({
content: 'Total = ' + total,
colSpan: 2
});
if (data.row.index === rows.length - 1) { doc.setFillColor(239, 154, 154); }
}
});
I'm pretty sure that I'm getting confused on how to face this problem. total
es with a number value but I want to print it in one custom last row alone but within the table, kind like an Excel rule would do.
Any suggestion would be helpful! Thank you.
I'm trying to build a small app with jspdf and jspdf-Autotable but I don't find how to create a custom last row with another variable value in an existing table.
What I just have done so far is this:
doc.autoTable({
body: concepts,
columns: [{ header: 'Concept', dataKey: 'name' }, { header: 'Amount', dataKey: 'amount' }],
didDrawPage: function (data) {
let rows = data.table.body;
rows.push({
content: 'Total = ' + total,
colSpan: 2
});
if (data.row.index === rows.length - 1) { doc.setFillColor(239, 154, 154); }
}
});
I'm pretty sure that I'm getting confused on how to face this problem. total
es with a number value but I want to print it in one custom last row alone but within the table, kind like an Excel rule would do.
Any suggestion would be helpful! Thank you.
Share Improve this question asked Apr 9, 2020 at 20:22 Rafael López DoradoRafael López Dorado 5371 gold badge4 silver badges16 bronze badges 01 Answer
Reset to default 5You have to add your custom data before processing the elements. Use ...
to destructure the data and merge with the new row.
function generate() {
var doc = new jsPDF();
var data = [
{name: "Bar", amount: 1200},
{name: "Zap", amount: 200},
{name: "Foo", amount: 320}];
var total = data.reduce((sum, el) => sum + el.amount, 0);
var body = [...data.map(el => [el.name, el.amount]),
[{content: `Total = ${total}`, colSpan: 2,
styles: { fillColor: [239, 154, 154] }
}]]
doc.autoTable({
head: [['Concept', 'Amount']],
body: body
});
doc.save("table.pdf");
}
<script src="https://unpkg./[email protected]/dist/jspdf.min.js"></script>
<script src="https://unpkg./[email protected]/dist/jspdf.plugin.autotable.js"></script>
<button onclick="generate()">Generate PDF</button>