我正在使用iText库创建可排序的表。为此,我试图隐藏/显示在同一位置创建的表。我读到这可以通过使用可选内容来实现。谁能帮我显示/隐藏带有可选内容的表格吗?

最佳答案

看一下SortingTable示例。在此示例中,我们将三个重叠的表添加到同一位置的文档中,但是由于每个表都属于无线电组的不同层,因此在同一时间只能看到一个表。您可以通过单击列标题切换到另一个表。

看看optionaltables.pdf。默认视图如下所示:

java - 如何隐藏和显示带有可选内容的表格-LMLPHP

但是,如果您单击“列2”一词,它看起来像这样:

java - 如何隐藏和显示带有可选内容的表格-LMLPHP

怎么做?

首先,我们创建OCG:

ArrayList<PdfLayer> options = new ArrayList<PdfLayer>();
PdfLayer radiogroup = PdfLayer.createTitle("Table", writer);
PdfLayer radio1 = new PdfLayer("column1", writer);
radio1.setOn(true);
options.add(radio1);
radiogroup.addChild(radio1);
PdfLayer radio2 = new PdfLayer("column2", writer);
radio2.setOn(false);
options.add(radio2);
radiogroup.addChild(radio2);
PdfLayer radio3 = new PdfLayer("column3", writer);
radio3.setOn(false);
options.add(radio3);
radiogroup.addChild(radio3);
writer.addOCGRadioGroup(options);


然后,使用ColumnText在同一位置添加3个表:

PdfContentByte canvas = writer.getDirectContent();
ColumnText ct = new ColumnText(canvas);
for (int i = 1; i < 4; i++) {
    canvas.beginLayer(options.get(i - 1));
    ct.setSimpleColumn(new Rectangle(36, 36, 559, 806));
    ct.addElement(createTable(i, options));
    ct.go();
    canvas.endLayer();
}


该表是这样创建的:

public PdfPTable createTable(int c, List<PdfLayer> options) {
    PdfPTable table = new PdfPTable(3);
    for (int j = 1; j < 4; j++) {
        table.addCell(createCell(j, options));
    }
    for (int i = 1; i < 4; i++) {
        for (int j = 1; j < 4; j++) {
            table.addCell(createCell(i, j, c));
        }
    }
    return table;
}


我们希望标题中的单词是可点击的:

public PdfPCell createCell(int c, List<PdfLayer> options) {
    Chunk chunk = new Chunk("Column " + c);
    ArrayList<Object> list = new ArrayList<Object>();
    list.add("ON");
    list.add(options.get(c - 1));
    PdfAction action = PdfAction.setOCGstate(list, true);
    chunk.setAction(action);
    return new PdfPCell(new Phrase(chunk));
}


在此POC中,表之间的差异与您想要的不同。您希望对内容进行不同的排序。对于这个简单的示例,我介绍了一种不同的背景色:

public PdfPCell createCell(int i, int j, int c) {
    PdfPCell cell = new PdfPCell();
    cell.addElement(new Paragraph(String.format("row %s; column %s", i, j)));
    if (j == c) {
        cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
    }
    return cell;
}

08-18 11:29
查看更多