如何在Java中设置iText PDF表格交替行颜色

6
我正在使用itext pdf库从数据库生成pdf文件。现在我需要的是,我必须以斑马条纹的颜色(灰色和白色)显示pdf表的交替行,但我不知道如何做...
这是我的代码...
        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"));
         }

请帮我一下。提前感谢。

2个回答

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

先生,我需要交替的行,但这里出现了交替的列。 - Adi
我在 PdfPRow r: table.getRows() 遇到了错误,提示类型不匹配:无法将元素类型从Object转换为PdfPRow。 - parlad
@parlad neupane 应该可以工作。您使用的itext和Java版本是什么? - Robin Green
使用 com.github.librepdf(openPdf)maven 依赖 v1.2.18,我遇到了相同的错误:Type mismatch: cannot convert from ArrayList to Object。解决方法是这样的...`for (Iterator i = pdfPTable.getRows().iterator(); i.hasNext();) { PdfPRow r = (PdfPRow) i.next(); ...}`但在这一行代码上出现了 NPE c.setBackgroundColor(b ? Color.RED : Color.WHITE);控制台记录 pdfPTable.size() 输出为 15。所以我知道行存在。 - user1653042

0

我使用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;
}

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