【问题标题】:How to set itext pdf table alernative rows colour in java如何在java中设置itext pdf表格替代行颜色
【发布时间】:2013-11-21 08:31:45
【问题描述】:

我正在使用 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"));
         }

请帮助我。 提前致谢。

【问题讨论】:

    标签: java pdf itext


    【解决方案1】:
    boolean b = true;
    for(PdfPRow r: table.getRows()) {
      for(PdfPCell c: r.getCells()) {
        c.setBackgroundColor(b ? BaseColor.GREY : BaseColor.WHITE);
      }
      b = !b;
    }
    

    【讨论】:

    • 先生,我需要交替的行,但这里是交替的列
    • 我在 PdfPRow r: table.getRows() 中遇到错误,说类型不匹配:无法从元素类型 Object 转换为 PdfPRow
    • @parlad neupane 应该可以工作。您使用的是什么版本的 itext 和 Java?
    • 使用 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。所以我知道行存在。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 2017-04-04
      • 1970-01-01
      • 2011-09-18
      • 2014-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多