如何使用jsPDF Autotable插件设置最后一行的样式

问题描述 投票:4回答:2

我使用jsPDFAutoTable创建基于表格的PDF文档:

var doc = new jsPDF('p', 'pt');
   //columns and rows are arrays created from the table content
        doc.autoTable(columns, rows, {

        drawRow: function (row) {
            if (row.index == rows.length - 1) {
                console.log('last row');
                //TODO
            }
        },
        pageBreak: 'avoid',
        headerStyles: {
            fillColor: [239, 154, 154],
            textColor: [0, 0, 0],
            halign: 'center'
        },
        bodyStyles: {
            halign: 'center'
        },
        margin: {top: 60},
        theme: 'striped'
    });

    doc.save('table.pdf');

我要做的是为最后一个表行设置不同的背景颜色。如上面的代码所示,我可以检测何时绘制最后一行,但是我无法修改它。我尝试使用RGB值设置row.fillColor,这似乎没有任何效果。

我也看了看examples,但在这个问题上找不到任何可以帮助我的东西。有任何想法吗?

javascript jspdf jspdf-autotable
2个回答
10
投票

您可以将drawRow的用法更改为drawCell,如下所示:

drawCell: function(cell, data) {
  var rows = data.table.rows;
  if (data.row.index == rows.length - 1) {
    doc.setFillColor(200, 200, 255);
  }
}

1
投票

自上次回答这个问题以来差不多已经过去了三年。我正在努力用drawCell函数实现这种效果。在jspdf-autotable": "^3.0.10"中,你应该使用以下三个回调之一来实现你想要的:

    // Use to change the content of the cell before width calculations etc are performed
    didParseCell: function (data) {
    },
    willDrawCell: function (data) { 
    },
    // Use to draw additional content such as images in table cells
    didDrawCell: function (data) {
    },

在你的情况下,willDrawCell是你想要使用的那个。所以代码将是这样的:

doc.autoTable({
  columns,
  body,
  headStyles: {
    fillColor: "#0d47a1"
  },
  willDrawCell: drawCell
});

let drawCell = function(data) {
  var doc = data.doc;
  var rows = data.table.body;
  if (rows.length === 1) {
  } else if (data.row.index === rows.length - 1) {
    doc.setFontStyle("bold");
    doc.setFontSize("10");
    doc.setFillColor(255, 255, 255);
  }
};
© www.soinside.com 2019 - 2024. All rights reserved.