iText | 无法设置单元格边框颜色

6

我正在尝试设置表格单元格的边框颜色。无论我尝试什么,边框颜色都不会改变 - 它总是黑色!我做错了什么?这是我的测试代码。 cell1 应该有一个红色的上边框和一个蓝色的下边框:

    PdfPTable table = new PdfPTable(2);

    PdfPCell cell1 = new PdfPCell(new Phrase("Cell 1"));
    cell1.setBorderColorTop(new BaseColor(255, 0, 0));
    cell1.setBorderColorBottom(BaseColor.BLUE);
    table.addCell(cell1);

    PdfPCell cell2 = new PdfPCell(new Phrase("Cell 2"));
    table.addCell(cell2);

非常好的问题!我自己也得查一下。我会创建一个示例来展示它是如何完成的。 - Bruno Lowagie
1个回答

10
请看ColoredBorder示例。我必须承认:iText存在不一致之处。
默认情况下,iText中所有边框都是相等的。如果您更改一个边框的颜色,则必须添加额外的线条:
cell = new PdfPCell(new Phrase("Cell 1"));
cell.setUseVariableBorders(true);
cell.setBorderColorTop(BaseColor.RED);
cell.setBorderColorBottom(BaseColor.BLUE);

使用setUseVariableBorders()方法,我们告诉iText边框不相等。如您所见,现在颜色得到了保留。

enter image description here

如果您更改边框的宽度,则不需要使用setUseVariableBorders()。在这种情况下,默认值会自动更改(这是我之前提到的不一致性):

cell = new PdfPCell(new Phrase("Cell 2"));
cell.setBorderWidthLeft(5);
cell.setBorderColorLeft(BaseColor.GREEN);
cell.setBorderWidthTop(8);
cell.setBorderColorTop(BaseColor.YELLOW);

如您所见,单元格1和单元格2仍然有两个黑色边框。我们可以使用 setBorder() 方法来删除它们:

cell = new PdfPCell(new Phrase("Cell 3"));
cell.setUseVariableBorders(true);
cell.setBorder(Rectangle.LEFT | Rectangle.BOTTOM);
cell.setBorderColorLeft(BaseColor.RED);
cell.setBorderColorBottom(BaseColor.BLUE);

如果您查看单元格2,您会发现我们选择了相当粗的边框。因此,这些边框与单元格中的文本重叠。我们可以使用setUseBorderPadding()方法避免这种情况:
cell.setBorder(Rectangle.LEFT | Rectangle.TOP);
cell.setUseBorderPadding(true);
cell.setBorderWidthLeft(5);
cell.setBorderColorLeft(BaseColor.GREEN);
cell.setBorderWidthTop(8);
cell.setBorderColorTop(BaseColor.YELLOW);

现在计算填充时将考虑边框。

非常感谢您的快速回复。您的解决方案有效!但是,我发现一些细微的差别阻止我创建完全干净的输出。当未设置变量边框时,似乎iText会进行一些智能边框折叠,以便相邻单元格之间只有一个边框。一旦我打开可变边框,我就开始看到不同颜色的双重和/或重叠边框。我的用例是具有黑色组边框的分组行和列的表格,除了每个垂直组中的最后一列具有LIGHT_GRAY左边框。 - Naresh
是的,只有两种解决方法可以避免这个问题:移除其中一个重叠的边框,或者使用单元格事件定义自定义边框 - Bruno Lowagie

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