简体   繁体   中英

How to set itext pdf table alernative rows colour in java

I am generating pdf file from database using itext pdf library.Now my need i that i have to show alternative rows of pdf table in different colour just like zebra colour (grey and white) but i dont know how to do that...

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("time"));
            table.addCell(rs.getString("source"));
            table.addCell(rs.getString("destination"));
            table.addCell(rs.getString("extension"));
         }

Please help me. Thanks in advance.

boolean b = true;
for(PdfPRow r: table.getRows()) {
  for(PdfPCell c: r.getCells()) {
    c.setBackgroundColor(b ? BaseColor.GREY : BaseColor.WHITE);
  }
  b = !b;
}

I do the following with iText 7

Table table = ...
int NUMBER_OF_ROWS = ...
Cell cell = null;
boolean condition = true;

for (int i = 0; i < NUMBER_OF_ROWS; i++) {

    cell = new Cell().add(new Paragraph("Column 1"));
    cell.setBackgroundColor(condition ? Color.GREY: Color.WHITE);
    table.addCell(cell);

    cell = new Cell().add(new Paragraph("Column 2"));
    cell.setBackgroundColor(condition ? Color.GREY : Color.WHITE);
    table.addCell(cell);

    cell = new Cell().add(new Paragraph("Column 3"));
    cell.setBackgroundColor(condition ? Color.GREY : Color.WHITE);
    table.addCell(cell);

    condition = !condition;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM