基于同一日期的 iText PDF 替代行颜色

iText PDF alternative row color on the basis of same date

我正在使用 iText PDF 库从数据库生成 PDF 文件。 现在我必须在同一日期的基础上以两种颜色(白色和黄色)显示 PDF table 的替代行。

这是我的代码:

PdfPTable table = new PdfPTable(10);
table.setTotalWidth(100);
table.setWidthPercentage(100);
while (rs.next()) {
    table.addCell(rs.getString("date"));
    table.addCell(rs.getString("destination"));
}

我添加了一个示例以便清楚地理解

如果您有两列,您应该在 PdfTable 构造函数中指定它。然后只是玩价值观:

PdfPTable table = new PdfPTable(2);
    table.setTotalWidth(100);
    table.setWidthPercentage(100);
    BaseColor color1 = WebColors.GetRGBColor("#FFFFFF");
    BaseColor color2 = WebColors.GetRGBColor("#00FFFF");
    String lastDateValue = "";
    BaseColor lastColor = color2;
    while (rs.next()) {
        String currentDateValue = rs.getString("date"));
        BaseColor color;
        if ( lastDateValue.equals(currentDateValue)){
            color = lastColor == color1 ? color1 : color2;
        } else {
            color = lastColor == color1 ? color2 : color1;
        }
        PdfPCell cell1 = new PdfPCell(new Phrase(currentDateValue));
        PdfPCell cell2 = new PdfPCell(new Phrase(rs.getString("destination")));
        cell1.setBackgroundColor(color);
        cell2.setBackgroundColor(color);
        table.addCell(cell1);
        table.addCell(cell2);
        lastDateValue = currentDateValue;
        lastColor = color
     }