How to adapt the position of the first line in ColumnText?

Tags: ColumnTextleadingascenderspacingiText 5

I'm dealing with a situation where I have a Phrase added to a ColumnText object.

The title in black is where iText is placing the text of the Phrase within the ColumnText. The title in pink is the desired placement. Is there anything I can do to tell iText not to put any space between the top of the highest glyphs (D and Z in this case) and the top of the ColumnText box?

Posted on StackOverflow on January 12, 2015 by Locriansax

Please take a look at the ColumnTextAscender example:

In both cases, I have drawn a red rectangle:

rect.setBorder(Rectangle.BOX);
rect.setBorderWidth(0.5f);
rect.setBorderColor(BaseColor.RED);
PdfContentByte cb = writer.getDirectContent();
cb.rectangle(rect);

To the left, you see the text added the way you do. In this case, iText will add extra space commonly known as the leading. To the right, you see the text added the way you want to add it. In this case, we have told the ColumnText that it needs to use the Ascender value of the font:

Phrase p = new Phrase("This text is added at the top of the column.");
ColumnText ct = new ColumnText(cb);
ct.setSimpleColumn(rect);
ct.setUseAscender(true);
ct.addText(p);
ct.go();

Now the top of the text touches the border of the rectangle.