Determine Appropriate Font-Size for Text iTextSharp


Background:
I use CorelDraw a lot to lay out my reports before writing the iTextSharp code to generate them. It gives me a fair idea of how to position report elements and keeps me from doing guesses or trial and error. This was the case when I worked on the ID Card project for Delta State University: I had the ID card neatly laid out and the school loved the design.

Issue:
Now, everyone knows we normally have long names in Nigeria. My design template had a name that was 10 characters long and I used 28pt points for this text. What I wanted to achieve however is that, for names that will not be able to fit into the maximum space allowed for the name text at the 28pt used in the design template, the system should use the maximum font size that will permit the name to fit in the space available. Its a simple problem, but wasn't so easy to resolve.

Solution:


 public Font GetSafeFont(string DisplayText, Font FontToUse, float SafeLength, float StartingSize)
        {
            /* Display Text: The text you wish to display in your PDF using iTextSharp 
             * FontToUse: The ideal Font definition for this text e.g  FontFactory.GetFont("Avenir Next", 15.5f, Font.BOLD, new BaseColor(16, 99, 166))
             * SafeLenght: Maximum allowed lenght for the display text according to your design template
             * StartingSize: The ideal Font size for the DisplayText
             */
            float FontSize = StartingSize, CurrentLenght;
            FontToUse.Size = StartingSize;
            Chunk NameChunk = new Chunk(DisplayText, FontToUse);
            //ensure that displaytext doesnt exceed safe lenght by finding the largest possible font size
            CurrentLenght = NameChunk.GetWidthPoint();
            while (CurrentLenght > SafeLength)
            {
                FontSize -= 0.5f;
                NameChunk.Font.Size = FontSize;
                CurrentLenght = NameChunk.GetWidthPoint();
            }
            Font NewFont = FontToUse;
            NewFont.Size = FontSize;
            return NewFont;
        }

Comments

  1. Daiwa Naga Phoenix - ion titanium hair color - Titanium Art
    Daiwa titanium frame glasses Naga Phoenix - ion titanium hair microtouch trimmer color. DANDAWA Naga ceramic vs titanium flat iron Phoenix – ion titanium hair color. DANDAWA Naga Phoenix - ion iron titanium token titanium hair fallout 76 black titanium color. DANDAWA Naga Phoenix.

    ReplyDelete

Post a Comment

Popular posts from this blog

Resize or Crop Image before Upload Using HTML5 File API

Exception from HRESULT: 0x80131040

Get Creative With Data Tables: Row Click Events