Java – iText: vertical alignment of pdftable cells

I tried to vertically align my avatar cell text 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 it doesn't work Sethorizontalalignment is centered but not setverticalalignment

Did I do something wrong? What should I do in the middle?

Any help will be welcome

Solution

According to lowagie:

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

This is always technically correct, but sometimes it looks bad

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

IText therefore finds the center of the phrase and aligns it But human eyes sometimes focus on most of the text, such as the font between the baseline and the height of the hat So to look good, you need to be relative to the center

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);

Notice that the pdfpcell method setverticalalignment (..) Not used

It seems that this does not necessarily apply to multiline phrases, but it does

If iText can display bounding boxes around things, this problem will be obvious (you can tell iText to draw bounding boxes, which is just more work than magic on / off switches)

This solution applies to email from Paulo soares

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>