I need to center the text inside a Pdf table cell. Unfortunately all the text is appearing at the Bottom of the cell. Here is my sample code:
String line = br.readLine();
Font f2 = new Font(Font.NORMAL, 12, Font.BOLD);
f2.setColor(Color.BLACK);
Paragraph p1 = new Paragraph(line, f2);
p1.setAlignment(Element.TABLE);
PdfPTable table = new PdfPTable(1);
table.setWidthPercentage(100);
PdfPCell cell = new PdfPCell();
cell.setBorder(Rectangle.NO_BORDER);
cell.setBorderWidthBottom(1f);
cell.setUseBorderPadding(true);
cell.setPadding(0);
cell.setBorderColor(new java.awt.Color(255, 255, 255));
cell.addElement(p1);
table.addCell(cell);
output.add(table);
I need the text inside the cell centered vertically inside the cell. Please help.
There are several errors in the snippet you shared. I've adapted the code and posted an example here http://itextpdf.com/sandbox/tables/CenteredTextInCell (dead link, now https://github.com/itext/i5js-sandbox/blob/master/src/main/java/sandbox/tables/CenteredTextInCell.java)
Reduced overview of changes:
The way you define a font is wrong, or you're using a version of iText that is really, really old.
The following line doesn't really make sense:
p1.setAlignment(Element.TABLE);
There is no such value in iText (there used to be one, but it has been removed a really long time ago) and evenso it doesn't make sense to use a value reserved to define an object type as to define an alignment.
If you don't want a border:
cell.setBorder(Rectangle.NO_BORDER);
It doesn't make sense to define border widths, padding or colors:
cell.setBorderWidthBottom(1f);
cell.setUseBorderPadding(true);
cell.setBorderColor(new java.awt.Color(255, 255, 255));
The line you need to define vertical alignment is:
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
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