Reputation: 1455
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.
Upvotes: 7
Views: 7262
Reputation: 3537
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;
}
Upvotes: 0
Reputation: 33033
boolean b = true;
for(PdfPRow r: table.getRows()) {
for(PdfPCell c: r.getCells()) {
c.setBackgroundColor(b ? BaseColor.GREY : BaseColor.WHITE);
}
b = !b;
}
Upvotes: 12