iText pdf library
Website search

How to choose the optimal size for a font?

Given a certain available width, how do I define the font size for a snippet of text, so that it matches the available width.

Posted on StackOverflow on Apr 12, 2013 by Mark Edwards

First you need a BaseFont object. For instance:

BaseFont bf = BaseFont.createFont(
    BaseFont.COURIER, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);

Now you can ask the base font for the width of this String in 'normalized 1000 units' (these are units used in 'Glyph space'; see ISO-32000-1 for more info):

float glyphWidth = bf.getWidth("WHAT IS THE WIDTH OF THIS STRING?");

Now we can convert these 'normalized 1000 units' to an actual size in points (actually user units, but let's assume that 1 user unit = 1 pt for the sake of simplicity).

For instance: the width of the text "WHAT IS THE WIDTH OF THIS STRING?" when using Courier with size 16pt is:

 float width = glyphWidth * 0.001f * 16f;

Your question is different: you want to know the font size for a given width. That's done like this:

 float fontSize = 1000 * width / glyphwidth;

Note that there are short cuts to get the widht of a String in points: you can use BaseFont.getWidthPoint(String text, float fontSize) to get the width of text given a certain fontSize. Or, you can put the string in a Chunk and do chunk.getWidthPoint() (if you didn't define a Font for the Chunk, the default font Helvetica with the default font size 12 will be used).

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