Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centered text in itext Pdf table cell

Tags:

java

cell

itext

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.

like image 650
Stanley Mungai Avatar asked Oct 31 '13 10:10

Stanley Mungai


2 Answers

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);
like image 75
Bruno Lowagie Avatar answered Sep 24 '22 23:09

Bruno Lowagie


cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
like image 21
Michele Mariotti Avatar answered Sep 26 '22 23:09

Michele Mariotti