iText pdf library
Website search

How to calculate/set font line distance?

I am implementing a PdfPageEventHelper event to add a footer as shown in this code snippet:


ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT,
    new Phrase(String.format(" %d ", writer.getPageNumber()), footerFont),
    document.right() - 2 , document.bottom() - 20, 0);
I need to add 3 lines, but I don't find how to calculate the distance between the lines. Each line has different font size. What should I use as XXX value in document.bottom() - XXX?

Posted on StackOverflow on Sep 17, 2013 by Dhaval

The difference between two lines is the leading. You can pick your own leading, but it is custom to use 1.5 times the font size. You are drawing line by line yourself, using different font sizes, so you'll have to adjust the Y value based on that font size. Note that ColumnText.showTextAligned() uses the Y value as the baseline of the text you're adding, so if you have some text with font size of 12pt, you'd need to take into account a leading of 18pt. If you have a font size 8pt, you make sure you have 12pt.

That's the easy solution: based on "convention". If you really want to know how much horizontal space some specific takes, you need to calculate the ascender and the descender. If bf is your font (a BaseFont object), text is your text (a String) and size is your font size (a float), then the height of your text is equal to height:

float aboveBaseline = bf.getAscentPoint(text, size);
float underBaseline = bf.getDescentPoint(text, size);
float height = aboveBaseline - underBaseline;

When y is the Y-coordinate used in showTextAligned() make sure you keep the space between y + aboveBaseline and y + underBaseline free. This is the accurate solution.

Note that document.bottom() - 20 looks somewhat strange. I would expect document.bottom() + 20 as the Y-axis of the PDF coordinate system points upwards, not downwards.

Click this link if you want to see how to answer this question in iText 7.

Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now