Home > Enterprise >  iText PDF alternative row color on the basis of same date
iText PDF alternative row color on the basis of same date

Time:12-19

I am generating PDF file from database using iText PDF library. Now I have to show alternative rows of PDF table in two colors (white and yellow) on the basis of same date.

Here is my code:

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

I have added an example for clear understanding

enter image description here

CodePudding user response:

If you have two columns you should specify it in the PdfTable constructor. Then isnjust playing with the values:

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
     }
  • Related