Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Fonts in System with iTextSharp

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

like image 383
techno Avatar asked Dec 12 '13 03:12

techno


People also ask

How do I change font size in Itextsharp?

The default font is Helvetica, 12pt, black in the style typically known as Normal. There are three principal ways to set the font to work with: one is to use the BaseFont. CreateFont() method, the second is to use the FontFactory. GetFont() method , and the third is to instantiate a new Font object.

How do I make my font bold in Itextsharp?

GetFont("verdana", 15, Font. BOLD)); It just makes Hello World bold.

What is Itextsharp in C#?

Itextsharp is an advanced tool library which is used for creating complex pdf repors. itext is used by different techonologies -- Android , . NET, Java and GAE developer use it to enhance their applications with PDF functionality.


2 Answers

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,fontName);
    }
    return FontFactory.GetFont(fontName, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); 
}
like image 123
VahidN Avatar answered Oct 08 '22 02:10

VahidN


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:

enter image description here

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

enter image description here

like image 31
Matthew Lock Avatar answered Oct 08 '22 03:10

Matthew Lock