Using Fonts in System with iTextSharp

2019-01-24 05:23发布

问题:

I want to use iTextSharp to write some text. I'm using this method:

var font = BaseFont.CreateFont(BaseFont.TIMES_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED);

My question is: does iTextSharp support all fonts in the system fonts directory?

Say I have a font called 'mycoolfont' selected by the user in the font chooser dialog. Can I create a new iTextSharp font like this?

var font = BaseFont.CreateFont("mycoolfont", BaseFont.WINANSI, BaseFont.EMBEDDED);
overContent.SetFontAndSize(font, fontSize);

UPDATE:

I tried var font = BaseFont.CreateFont("Verdana", BaseFont.WINANSI, BaseFont.EMBEDDED); but got the error "Verdana" is not recognized by itextsharp

回答1:

1st you need to register the font and then just retrieve it from the FontFactory (and don't create it every time):

public static iTextSharp.text.Font GetTahoma()
{
    var fontName = "Tahoma";
    if (!FontFactory.IsRegistered(fontName))
    {
         var fontPath = Environment.GetEnvironmentVariable("SystemRoot") + "\\fonts\\tahoma.ttf";
         FontFactory.Register(fontPath);
    }
    return FontFactory.GetFont(fontName, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); 
}


回答2:

I ended up combining the 2 answers here into this method:

public static Font GetFont(string fontName, string filename)
{
    if (!FontFactory.IsRegistered(fontName))
    {
        var fontPath = Environment.GetEnvironmentVariable("SystemRoot") + "\\fonts\\" + filename;
        FontFactory.Register(fontPath);
    }
    return FontFactory.GetFont(fontName, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
}

Which I then use in my code like so:

writer.DirectContent.SetFontAndSize(GetFont("Franklin Gothic Medium Cond", "FRAMDCN.TTF").BaseFont, 24f);

On Windows you can find out the font's file name from the font's property sheet:

I also found that you have to use the font's exact name on the Details tab:



回答3:

Im posting this since someone else might find this useful. I had a similar problem when i ran my code on server. The reason being itextsharp could not find the font style in OS. My PDF showed some random font style when it could not find the font(dint throw error). I copied the required font files (.ttf) to my project bin folder and used following code.

public static BaseFont GetFont(string fontName)
{
    return BaseFont.CreateFont(HttpContext.Current.Server.MapPath("~/Bin/" +   fontName + ".ttf"), BaseFont.CP1252, BaseFont.EMBEDDED);
}

Here i get the desired font

`BaseFont sm = GetFont("comic"); //The fontName here should exactly match` the` file name in bin folder