Search code examples
c#itextfont-style

iTextSharp apply font style to existing font


In the beginning of a document I created a new font:

BaseFont baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\Calibri.ttf", "Identity-H", BaseFont.EMBEDDED);
var font1 = new Font(baseFont, 12, Font.NORMAL);

Somewhere in the middle of the same document I want to use the same font (fontfamily & size) with different style: bold & italic.

Can I somehow change the style of font1 or do I have to create a new Font?

Note: I know I can do:

font1.SetStyle("bold");
font1.SetStyle("italic");

but how about both? And maybe also underline...


Solution

  • First of all, in

    BaseFont baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\Calibri.ttf", "Identity-H", BaseFont.EMBEDDED);
    

    you load the font file for regular Calibri. If you derive any Font from this BaseFont, it uses the regular Calibri font file, no matter which style attributes you set. This in particular means that

    • a "bold" style is implemented by not only filling the normal glyph contour but also stroking a line along it (a variant of what's called "poor man's bold") and
    • an "italic" style is implemented by applying a transformation matrix which skews a bit.

    You get better quality bold and italic variations by loading the bold or italic Calibri

    BaseFont baseFontBold = BaseFont.CreateFont(@"C:\Windows\Fonts\Calibrib.ttf", "Identity-H", BaseFont.EMBEDDED);
    BaseFont baseFontItalic = BaseFont.CreateFont(@"C:\Windows\Fonts\Calibrii.ttf", "Identity-H", BaseFont.EMBEDDED);
    BaseFont baseFontBoldItalic = BaseFont.CreateFont(@"C:\Windows\Fonts\Calibriz.ttf", "Identity-H", BaseFont.EMBEDDED);
    

    and deriving a Font with style "normal" from the matching BaseFont.


    That been said, now to your main question:

    I know I can do:

    font1.SetStyle("bold");
    font1.SetStyle("italic");
    

    but how about both? And maybe also underline...

    For both you can simply do as you wrote

    font1.SetStyle("bold");
    font1.SetStyle("italic");
    

    i.e. setting both sequentially, because SetStyle(String) actually works more like an AddStyle. Alternatively, though, you can also do

    font1.SetStyle("bold italic");
    

    If you need to reset the set of selected styles to normal, you can use SetStyle(int) which really works like a setter should:

    font1.SetStyle(0);
    

    And maybe also underline...

    The String constants for the available styles are

    • "normal"
    • "bold"
    • "italic"
    • "oblique"
    • "underline"
    • "line-through"