最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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 0
Add a ment  | 

1 Answer 1

Reset to default 5

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./[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>

发布评论

评论列表(0)

  1. 暂无评论