如何使用jsPDF Autotable插件来为最后一行添加样式?

9

我使用 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,但似乎没有效果。
我还查看了示例,但没有找到任何可以帮助我解决这个问题的东西。有什么想法吗?

1
我猜你创建了 jspdf-autotable 标签。谢谢! - Simon Bengtsson
@SimonBengtsson 是的,我确实这样做了,因为我有点生气,谷歌搜索我的问题没有引导我到很多SO帖子;)像你的AutoTable插件这样有用的东西在我看来应该更受欢迎。 - Droidman
2个回答

22

要动态更改样式,您有两个选项。第一种是使用didParseCell来更改autoTable的样式:

doc.autoTable({
    html: '#table',
    didParseCell: function (data) {
        var rows = data.table.body;
        if (data.row.index === rows.length - 1) {
            data.cell.styles.fillColor = [239, 154, 154];
        }
    }
});
第二种方法是使用willDrawCell,如果您更喜欢使用jspdf样式函数:
doc.autoTable({
    html: '#table',
    willDrawCell: function (data) {
        var rows = data.table.body;
        if (data.row.index === rows.length - 1) {
            doc.setFillColor(239, 154, 154);
        }
    },
});

查看更高级的示例,请点击这里


6

距离最后一次回答这个问题已经快三年了。 我在使用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);
  }
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接