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

时间:2016-03-01 10:45:01

标签: javascript jspdf jspdf-autotable

我使用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,但在这个问题上找不到任何可以帮助我的东西。有什么想法吗?

2 个答案:

答案 0 :(得分: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 :(得分:0)

自上次回答此问题以来已经快三年了。 我在用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);
  }
};