iTextSharp - Working with Fonts

Following on from my introduction to iTextSharp, the free PDF utility that lets you work with PDF files within ASP.NET, this article looks at working with fonts in PDF documents that you create. If you haven't read the first article in this series, I recommend that you do so now.

iTextSharp has built-in support for the 14 Type 1 fonts: Courier, Courier Bold, Courier Italic, Courier Bold and Italic, Helvetica, Helvetica Bold, Helvetica Italic, Helvetica Bold and Italic, Times Roman, Times Roman Bold, Times Roman Italic, Times Roman Bold and Italic, Symbol, ZapfDingBats®. Helvetica translates more or less to Windows Arial font, while Times Roman has an equivalent in Times New Roman. 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. BaseFont.CreateFont() is a lot more limited, and only sets up the definition of a font. new Font() allows for propogation of font styles from one font to the next. FontFactory.GetFont() returns a valid and new Font object that you can work with directly. It also offers 14 overloaded constructors which gives you a lot more options to work with. For that reason, you are most likely going to use the FontFactory.GetFont() method. But we will get BaseFont.CreateFont() out of the way first.

 

BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);

Font times = new Font(bfTimes, 12, Font.ITALIC, Color.RED);

 

The above lines create a BaseFont object and uses the built-in constant values to set the font family and encoding. It also specifies false for embedding the font within the PDF document. this decreases the overall size of the document, but should be set to true if you are using fonts that are unlikely to be on the user's system, or if you plan to get the PDF printed professionally. A new Font object is created using the BaseFont object, and further setting the font size in points, the style and the colour - again, using iTextSharp's constants for these values. Now the font is put to use in a paragraph:

 

string path = Server.MapPath("PDFs");

Document doc = new Document();

PdfWriter.GetInstance(doc, new FileStream(path + "/Font.pdf", FileMode.Create));

doc.Open();

doc.Add(new Paragraph("This is a Red Font Test using Times Roman", times));

doc.Close();

 


And the result (if all goes well) is as follows:

Now to the FontFactory.GetFont() method. This method has 14 (count 'em!) overloads that allow you to specify anything from font family, size, colour, style, embedding, encoding and caching in pretty much any combination you like. Each time that you call FontFactory.GetFont(), a new Font object is created. This method will work directly with all fonts registered by iTextSharp, which includes all fonts found in the Windows default font directory. On Win XP Pro, that's usually C:/WINDOWS/Fonts. If you want a list of all the registered fonts, the FontFactory.RegisteredFonts collection holds them. This can be useful if you want to find the exact name of each font.

int totalfonts = FontFactory.RegisterDirectory("C:\\WINDOWS\\Fonts");

StringBuilder sb = new StringBuilder();

foreach (string fontname in FontFactory.RegisteredFonts)

{

  sb.Append(fontname + "\n");

}

doc.Add(new Paragraph("All Fonts:\n" + sb.ToString()));

 

Here's a variety of ways to use the GetFont() method:

 

Font arial = FontFactory.GetFont("Arial", 28, Color.GRAY);

Font verdana = FontFactory.GetFont("Verdana", 16, Font.BOLDITALIC, new Color(125, 88, 15));

Font palatino = FontFactory.GetFont(

 "palatino linotype italique",

  BaseFont.CP1252,

  BaseFont.EMBEDDED,

  10,

  Font.ITALIC,

  Color.GREEN

  );

Font smallfont = FontFactory.GetFont("Arial", 7);

Font x = FontFactory.GetFont("nina fett");

x.Size = 10;

x.SetStyle("Italic");

x.SetColor(100, 50, 200);

 

As you can see, some of them use the iTextSharp Color object to set the colour using a constant, while others use the SetColor() method and pass in RGB values or create a new Color object passing in RGB values. Generally, they use a constant value for the font style, but you can pass in an int representing one of the values, or use the SetStyle() method passing in a string. There are also varying numbers of parameters passed, which ilustrates some of the different overloads available. Intellisense, Code Complete and the Object Browser will reveal the full panoply of options.

Registering Fonts

You may have a situation where you cannot install a font you want to use in the default font directory on the web server, so you have to register it explicitly with iTextSharp.

 

string fontpath = Server.MapPath(".");

BaseFont customfont = BaseFont.CreateFont(fontpath + "myspecial.ttf", BaseFont.CP1252, BaseFont.EMBEDDED);

Font font = new Font(customfont, 12);

string s = "My expensive custom font.";

doc.Add(new Paragraph(s, font));

 

You may notice that the above example is embedded in the PDF file (BaseFont.EMBEDDED), as your expensive font is unlikely to exist on users' operating systems.

Date Posted:
Last Updated:
Posted by:
Total Views to date: 306054

27 Comments

- janak

How can I change the Default Font Size?
Presently in my Project if I am not set font for Paragraph
then it will automatically take Arial Font Size 12.
How Can I change the size of Default Font?

- Mike

@Janak,

If all you want to do is, say, reduce the font to 10pt, something like FontFactory.GetFont(FontFactory.HELVETICA, 10) will do you.

- Ali

Nice article.. help me a lot.
I have a question that can i create a pdf with right to left language like URDU.
when i write urdu text in paragraph then it creates empty pdf. so can u help me to incorporate my task.

Thanks

- Mihai

how can I set a default font for the entire document and only in special cases use different fonts?

- manoj

not satisfy with the answer of my question so kindly send me full code if possible at my mail Id

- Mike

@manoj

If my article doesn't answer your "question" satisfactorily, how can I possibly know what code will help you?

- Arin

Hello,

I am using ITextSharp to parse html to PDF. But the problem it didn't take any fonts within HTML. For example; suppose the following code snippet is my html

<span style="font-family: comic sans ms; font-size: 20px; color: #FF0000;">Hello its Arin. </span><span style="font-family: verdana; font-size: 20px; color: #FF0000;">Its a Test HTML page.</span>

now if you parse this...you will get the PDF without the font style.

Please let me know if you have any idea.

- Mike

@Arin

iTextSharp is not very good with HTMl, as I am sure you have discovered. You will need to set up your own styles within the PDF using iTextSharp's StyleSheet classes.

- helpful?

Great articles, thanks! How about foward/backward links throughout the series, just so we don't miss any?

- PRa

@Arin - have you found the solution to this? I have the exact same problem, the font sizes and other html formatting are coming through in the pdf but not font styles.. I checked that link provided but that StyleSheet() only describes adding definitions for tags like body, span, but I have multiple span tags and they each can have different font style definitions..

- Peter

Hello Mike,
Thank you for the great articles. One question, is it possible to select a different font for each cell in a table? And if so, how? :)

thanks again.

- Mike

@Peter

Yes it's possible. This article shows how:

http://www.mikesdotnetting.com/Article/86/iTextSharp-Introducing-Tables

- Kjetil Myhre

Thanks for your great examples, which I use extensively to create my own PDFs. :)

I notice that you are using color constants and create RGB-colors. I'm currently trying out CMYK-based colors, but I can't seem to get them to work properly.

For instance I am unable to get the font color black. It just becomes a darkish kind of gray. For black I've tried both CMYK(0,0,0,100) and CMYK(100,100,100,100), but none of them gives black. I also try a a few different shades of blue, but they are nowhere near the real deal which I pick from http://kuler.adobe.com/#create/fromacolor (an excellent color tool, for those unfamiliar with it)

Do you have any experience with iTextSharp and CMYK colors?

- jen

Hi,

Do you know how to apply fonts when using pdfstamper and a fillable pdf template?

I've tried applying font to the OverContent as well as setting field properties of "textfont" but it all seems to be being ignored.

Unfortunately all the font samples seem to involve adding paragraphs and chunks :(

Thanks!!

- chary

HI Mikes,

thanks for the article.
Am having one problem in pdf conversion using itextsharp. bullets are not displaying properly, which is in html encoded text and HTMLWorker.ParseToList to partse. It is using Wingdlings font and is not coming proper in pdf. Is there a workaround for this issue.

Thanks

- Ryan

A couple tips for writing Japanese text from code. Hope this helps ppl from bashing their heads into keyboard.

1) MS-Gothic is found on most windows computers with default installation. You don't need to download any special true type font files if you don't want to.

//here is the font object
Font fMSGothic = FontFactory.GetFont("MS-PGothic", BaseFont.IDENTITY_H, 8);

//using baseic Document and PdfWriter objects
table.AddCell(new Phrase("名字", fMSGothic));

//using PdfStamper and AcroFields objects
//filePath = location of template with fields to populate
//newFilePath = location to save new file with fields populated.
PdfReader reader = new PdfReader(filePath);
PdfStamper stamper = new PdfStamper(reader, new FileStream( newFilePath, FileMode.Create));
AcroFields fields = stamper.AcroFields;

foreach (DictionaryEntry de in fields.Fields)
{
string name = de.Key.ToString();
string data = "名字";

fields.SetFieldProperty(name, "textfont", fMSGothic.BaseFont, null);
fields.SetField(name, data);

}


- Joey

Hello Mike,

Why am I getting this error when converting to vb.net? ("System.Drawing.Color.Friend Sub New(knownColor As System.Drawing.KnownColor)' is not accessible in this context because it is 'Friend'")

Dim verdana As Font = FontFactory.GetFont("Verdana", 16, Font.BOLDITALIC, New System.Drawing.Color(125, 88, 15))

Thanks Mike!

- turbolence

The Color.RED should be changed in BaseColor.RED

- gürhan

thanks thanks thanks

- Spanner

I have a new font stored in my database. Is there a way to embed the font to an existing pdf?
I have been playing around with pdfStamper and PdfContentByte and I have managed to use the new font for new text but I need to change the whole pdf to the new font. I don't need to add anything new to it. This pdf also includes tables.

- jake

i get this error when trying to appy font:

Error10 'Font' is ambiguous, imported from the namespaces or types 'System.Drawing, iTextSharp.text'.

I am working in vb

- Mike

@jake

You can use an alias when importing one of the namespaces to avoid collisions: http://msdn.microsoft.com/en-us/library/zt9tafza(v=vs.110).aspx

- MilanSxD

@Arin and @PRa - To make the font styles work in iTextSharp, you need to remove the quotes in the CSS.

So font-style: "verdana";
becomes font-style: verdana;

- lama

thanks alot!!
is it possible to add line height value to a paragraph ?

- Vimal

I want to edit my existing PDF.
I want to change font color. I want to change is gray or some lighter color. I want to reduce color darkness with 10%, 15%, 20% like this....
Is it possible ?
also want to change image in gray..

- Anthony

Hi, is it possible to set formatting of only some of the text within a single field? For instance, if a field contains the text "This is some awesome text" and I'm wanting to bold "This" and italicize "awesome", is this possible in any way using iText? Thanks!

- Mike

@Anthony

Look at the use of Chunks in the next article in the series: iTextSharp - Adding Text with Chunks, Phrases and Paragraphs

Recent Comments

Justin Kusuma 8/4/2015 7:01 AM
In response to Posting Data With jQuery AJAX In ASP.NET Razor Web Pages
Hi Mike, thanks for replying... I'm looking for more elegant way to provide user feedback. As now...

Arthur 8/3/2015 4:54 PM
In response to Getting the identity of the most recently added record
Thanks Mike, your site is a mine of useful info :)...

MRP 8/3/2015 4:06 AM
In response to Entity Framework Recipe: Many To Many Relationship On The Same Table
my question is about HashSet and ICollection ! why you use this type and why not user Ilist<> and ?...

Arbaz 8/1/2015 3:39 PM
In response to Scheduled Tasks In ASP.NET With Quartz.Net
Hey Mike, What If I want to set a schedule weekly or every Sunday to run. What would the code for I...

Emma 7/31/2015 3:29 AM
In response to How To Send Email In ASP.NET MVC
As mentioned by John Noble, there seems to be something missing in regards to: return...

Satyabrata Mohapatra 7/30/2015 6:42 AM
In response to Implementing Google's EU End User Consent Policy
Thanks.... Learned a lot....

Jaswanth 7/29/2015 1:31 PM
In response to Displaying Google Analytics Data in ASP.NET
Hi Mike, My application uses MVC 1. I need to fetch the data of pages which has top views. I tried...

Sergey 7/28/2015 6:48 AM
In response to Custom TagHelpers in ASP.NET MVC 6
Thanks a lot!...

Dome 7/27/2015 7:55 PM
In response to Posting Data With jQuery AJAX In ASP.NET Razor Web Pages
Hi, I've just created a new project with WebApi & MVC, then created a controller with the following...

Ted Driver 7/26/2015 5:44 PM
In response to How To Send Email In ASP.NET MVC
Thanks for the great example Mike! I noticed in my implementation of your code that if I put some in...