9

I am using com.lowagie.text to create PDF in my code. All is working fine except I am trying to align my cell content vertically. I want cell text to be in the middle of the cell height.

This is my code

PdfPCell cell = new PdfPCell(new Phrase(value, fontValueNew));
cell.setBorder(o);
cell.setBackgroundColor(new Color(233,232,232));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);

Here ,horizontal alignment is working fine but vertical alignment is not effective.

user1516873
  • 5,060
  • 2
  • 37
  • 56
Anupam Sharma
  • 1,529
  • 1
  • 14
  • 33

3 Answers3

0

I'm not too sure as to why, but this works for me (vertical center alignment):

String headingLabel = "Test";

Paragraph heading = new Paragraph(headingLabel,
        new Font(helvetica, 28, Font.NORMAL, new BaseColor(0, 0, 0)));

Float textWidth = ColumnText.getWidth(heading);
Float maxAllowed = 630f;

while (maxAllowed < textWidth) {
    fontSize -= 2;
    heading = new Paragraph(headingLabel,
        new Font(helvetica, fontSize, Font.NORMAL, new BaseColor(0, 0, 0)));
    textWidth = ColumnText.getWidth(heading);
}

heading.setAlignment(Element.ALIGN_CENTER);

PdfPCell titleCell = new PdfPCell();
titleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
titleCell.setVerticalAlignment(Element.ALIGN_TOP);
titleCell.addElement(heading);
titleCell.setFixedHeight(65f);
headerTable.addCell(titleCell);
epoch
  • 16,396
  • 4
  • 43
  • 71
0

ALIGN_MIDDLE has integer value 5 defined in the the iText code. Please pay attention while you are writing ALIGN_MIDDLE a tip comes up "Possible value for vertical element." It means if your element is in vertical orientation then it will work as it calculates the center of the element. My suggestion is to replace ALIGN_MIDDLE with ALIGN_CENTER so your code will look like:

cell.setVerticalAlignment(Element.ALIGN_CENTER);
V Malhi
  • 19
  • 6
0

Try this:

PdfPCell cell = new PdfPCell(new Phrase(value, fontValueNew));
cell.setBorder(o);
cell.setBackgroundColor(new Color(233,232,232));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_CENTER);
Luan Vo
  • 221
  • 3
  • 8