How to add a custom last row within a table using jspdf-Autotable

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 comes 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.

Upvotes: 3

Views: 6151

Answers (1)

ariel
ariel

Reputation: 16150

You 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.com/[email protected]/dist/jspdf.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/jspdf.plugin.autotable.js"></script>
<button onclick="generate()">Generate PDF</button>

Upvotes: 5

Related Questions