how to set outline border for pdf table using itext pdf java
________________________________________
| cell 1 cell2 cell3 cell4 |
| cell 5 cell2 cell3 cell4 |
| cell 9 cell2 cell3 cell4 |
| cell 1 cell2 cell3 cell4 |
| cell 1 cell2 cell3 cell4 |
|________________________________________|
In iText 7, see Chapter 5 of the "iText 7: building blocks" tutorial, where we create this table:

The code can be found here: CellBorders
Table table2 = new Table(new float[]{2, 1, 1});
table2.setMarginTop(10);
table2.setBorder(new SolidBorder(1));
table2.setWidthPercent(80);
table2.setHorizontalAlignment(HorizontalAlignment.CENTER);
table2.addCell(new Cell(1, 3)
.add("Cell with colspan 3").setBorder(Border.NO_BORDER));
table2.addCell(new Cell(2, 1)
.add("Cell with rowspan 2").setBorder(Border.NO_BORDER));
table2.addCell(new Cell()
.add("row 1; cell 1").setBorder(Border.NO_BORDER));
table2.addCell(new Cell()
.add("row 1; cell 2").setBorder(Border.NO_BORDER));
table2.addCell(new Cell()
.add("row 2; cell 1").setBorder(Border.NO_BORDER));
table2.addCell(new Cell()
.add("row 2; cell 2").setBorder(Border.NO_BORDER));
document.add(table2);
In iText 5, you have to set all the borders of all the cell to NO_BORDER, and you have to draw the border of a table by using a table event. This is explained in chapter 5 of the book "iText in Action - Second Edition", more specifically in the PressPreviews example.
This is the table event you need:
public class MyTableEvent implements PdfPTableEvent {
public void tableLayout(PdfPTable table, float[][] width, float[] height,
int headerRows, int rowStart, PdfContentByte[] canvas) {
float widths[] = width[0];
float x1 = widths[0];
float x2 = widths[widths.length - 1];
float y1 = height[0];
float y2 = height[height.length - 1];
PdfContentByte cb = canvas[PdfPTable.LINECANVAS];
cb.rectangle(x1, y1, x2 - x1, y2 - y1);
cb.stroke();
cb.resetRGBColorStroke();
}
}
You declare this event to the table like this:
table.setTableEvent(new MyTableEvent());
make sure that the cell don't have any borders!
Important: if you are starting a new project with iText, you should consider using iText 7. As you can see, there were quite some changes to the API.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With