Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iText | Can't set cell border color

Tags:

itext

I am trying to set border colors of table cells. No matter what I try, the border color is not changing - it's always black! What am I doing wrong? Here's my test code. cell1 should have a red top border and a blue bottom border:

    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);
like image 873
Naresh Avatar asked Jan 28 '16 22:01

Naresh


1 Answers

Please take a look at the ColoredBorder example. I have to admit: there's an inconsistency in iText.

By default, all borders are equal in iText. If you change the color of one border, you have to add an extra line:

cell = new PdfPCell(new Phrase("Cell 1"));
cell.setUseVariableBorders(true);
cell.setBorderColorTop(BaseColor.RED);
cell.setBorderColorBottom(BaseColor.BLUE);

With the setUseVariableBorders() method, we tell iText that the borders aren't equal. As you can see, the colors are now respected:

enter image description here

Using setUseVariableBorders() isn't necessary if you change the width of a border. In that case, the default is change automatically (this is the inconsistency I mentioned earlier):

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

As you can see, there are still two black borders in cell 1 and cell 2. We can remove these with the setBorder() method:

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

If you look at cell 2, you see that we have chosen rather thick borders. As a result these borders overlap with the text in the cell. We can avoid this with the setUseBorderPadding() method:

cell.setBorder(Rectangle.LEFT | Rectangle.TOP);
cell.setUseBorderPadding(true);
cell.setBorderWidthLeft(5);
cell.setBorderColorLeft(BaseColor.GREEN);
cell.setBorderWidthTop(8);
cell.setBorderColorTop(BaseColor.YELLOW);

Now the border will be taken into account when calculating the padding.

like image 160
Bruno Lowagie Avatar answered Nov 12 '22 10:11

Bruno Lowagie