iText pdf library
Website search

How do I change the border color of a PdfPCell?

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));
PdfPCell cell2 = new PdfPCell(new Phrase("Cell 2"));
Question posted on StackOverflow on Jan 29, 2016 by Naresh

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"));

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

Different cell border widths and colors
Different cell border widths and colors

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"));

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.setBorder(Rectangle.LEFT | Rectangle.BOTTOM);

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);

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

Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now