Dynamically adjust font size of text to fit into a PDF text field using iTextSharp.LGPLv2.Core.

Tai Bo
4 min readJan 23, 2021
Image by S K from Pixabay

In one of the asp.net core projects I worked on, I used iTextSharp.LGPLv2.Core to programmatically fill out a PDF form. Sometimes, we have a string that is too long to fit within the rectangle area of the text field. After a bit of googling, I found and adopted the solution in this StackOverFlow to solve this problem by dynamically compute the appropriate font size I can use so that the value can fit within the field.

The logic is fairly straightforward.

  1. Find the current font size and width of the text field.
  2. Compute the width of the value using the current font size as the starting point.
  3. Keep reducing the font size until the width of the value is less than or equal to the width of the text field.
  4. Set the font size of the text field to the final font size.

Find the width of a text field

A PDF text field is basically a rectangular container and we can compute the width using the left and right positions of the container on the page, as the below snippets demonstrate.

        /// <summary>
/// Helper method to compute the width of a field's container
/// </summary>…

--

--

Tai Bo
Tai Bo

Written by Tai Bo

Backend developer in .NET core. I enjoy the outdoor, hanging out with good friends, reading and personal development.

No responses yet