简体   繁体   中英

iText: PdfTable cell vertical alignment

I'm trying to vertical align my headet cell text to be in the middle of the cell height.

This is my code:

    PdfPCell c1 = new PdfPCell(cerate_phrase("" ,regular_bold ));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    c1.setVerticalAlignment(Element.ALIGN_MIDDLE);
    c1.setBackgroundColor(BaseColor.LIGHT_GRAY);
    table_.addCell(c1);

but this does not work. setHorizontalAlignment is centered but not setVerticalAlignment .

Am I doing something wrong? how can i vertically align it in the middle?

Any help will be appreciated.

According to Lowagie:

PdfPCell cell = new PdfPCell(new Phrase("blah Blah blah");
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);

This is always correct in a technical sense, but sometimes looks bad.

To center, draw a box around the object, find its middle, and align it with the center of its surrounding object.

iText thus finds the center of the phrase, and aligns it. But human eyes sometimes focus on the bulk of text, say the parts of the font between the baseline and the cap height. So to have it look good, you need to center relative to that.

Phrase content = new Phrase("Blah blah blah", Font);

Float fontSize = content.getFont().getSize();
Float capHeight = content.getFont().getBaseFont().getFontDescriptor(BaseFont.CAPHEIGHT, fontSize);

Float padding = 5f;    

PdfPCell cell = new PdfPCell(content);
cell.setPadding(padding);
cell.setPaddingTop(capHeight - fontSize + padding);

Note that the PdfPCell method setVerticalAlignment(..) isn't used.

It seems like this wouldn't necessarily work for a multi-line phrase, but it does.

排版行术语

The problem would be obvious if iText could show bounding boxes around things (mind, you can tell iText to draw bounding boxes, it's just more work than a magical on/off switch).

This solution is adapted from an email from Paulo Soares .

Add cell.setUseAscender(true) before c1.setVerticalAlignment(Element.ALIGN_MIDDLE); I have the same problem with you, when add code above I find it can work, hope this can solve your problem, thanks.

You can use the option ExtraParagraphSpace :

c1.HorizontalAlignment = Element.ALIGN_CENTER;
c1.VerticalAlignment = Element.ALIGN_MIDDLE;
c1.ExtraParagraphSpace = 2;

You cant do like this :

cell.setBackgroundColor(BaseColor.GRAY);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setUseAscender(true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM