Dynamically adjust font size of text to fit into a PDF text field using iTextSharp.LGPLv2.Core.
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.
- Find the current font size and width of the text field.
- Compute the width of the value using the current font size as the starting point.
- Keep reducing the font size until the width of the value is less than or equal to the width of the text field.
- 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>…