Search code examples
c#alignmentitext

How to tweak the vertical position of text in a cell?


I have a problem with the vertical alignment in a table. The text is too close to the bottom border:

enter image description here

My code looks like this:

nested = new PdfPTable(3);
nested.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
nested.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
nested.WidthPercentage = 100;
nested.AddCell(new Phrase("blablabla"));
nested.AddCell(new Phrase("blablabla"));
nested.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
nested.AddCell(new Phrase("Stand: " + 
pdfdoc.Add(nested);

Adding or removing the line DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE; doesn't have any effect.


Solution

  • You are creating PdfCell object with only one line of text. The height of the cell will be determined based on that line of text. The text will be aligned in the middle automatically. That explains why adding or removing DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE; has no effect: as far as iText is concerned, the text is already aligned in the middle.

    You claim that this isn't true because it's your perception that the base line of the text is too close to the bottom. I understand that claim, but if your read my answer to the question How does a PdfPCell's height relate to the font size? you should understand which factors create that perception:

    1. The leading: the default font size is 12 pt; the default leading is 18 pt. A leading of 18 pt is kind of high and results in extra space above the base line. If you reduce the leading, you'll see that there's less space at the top.
    2. Different fonts have different ascender and descender values; the way you add the cells, iText won't take those values into account.

    My suggestion: tell iText to use the ascender and descender of the font you're using:

    nested.DefaultCell.UseAscender = true;
    nested.DefaultCell.UseDescender = true;
    

    You'll notice that the position of the text will already be much better. If it's not better, you may want to add some padding. All of this is, of course, explained in the official documentation where you'll find an example called Spacing.cs. Try this example and you'll see how the position of the content changes by tweaking values such as UseAscender, UseDescender, Padding, and so on.