Skip to main content

How to use Font Awesome with IText

This post is about on how to use Font Awesome with IText library to generate awesome icons in our PDF documents. In this post, we are using ITextSharp, a C# port for IText, but those are the same functionalities.

Download PDF example

Prerequisites:
  1. Download the Font Awesome resources from fontawesome.io/ and copy it in the project. Remark: isn't needed to install the fonts on the operative system.
  2. Install the ITextSharp dependency (you can use the NuGet package manager).

public class ExampleITextAndFontAwesome
{
    static void Main(string[] args)
    {
        // Set the PDF file
        FileStream fs = new FileStream("example-fontawesome-itext.pdf", 
                FileMode.Create, FileAccess.Write, FileShare.None);
        
        // Create document
        Document doc = new Document(new Rectangle(PageSize.LETTER));
        PdfWriter writer = PdfWriter.GetInstance(doc, fs);
        doc.Open();
        doc.NewPage();

        // Registe Font Awesome
        FontFactory.Register("fontawesome-webfont.ttf", "font-awesome");
        Font fontAwesome = FontFactory.GetFont(
                "font-awesome",
                BaseFont.IDENTITY_H,
                BaseFont.EMBEDDED,
                12,
                Font.NORMAL,
                BaseColor.BLACK);

        // Create a text and icon
        Paragraph paragraph = new Paragraph();
        paragraph.Add(new Chunk("Hello world! "));
        paragraph.Add(new Chunk("\xf118", fontAwesome));
        doc.Add(paragraph);

        doc.Close();
    }
}

First, we need to register the font Font Awesome on IText. To do this, you need to set up the font file and other params like font size, style, and color. You need to set BaseFont.IDENTITY_H in order to use Unicode encode in that font.

In order to add a Font Awesome icon, you might use a Chunk instance on a Paragraph. It's needed to specify it's code and the font you want to use. You can get the codes from fontawesome.io/cheatsheet/.


Remark: to use the codes from the previous page, you must remove the characters "&#" and ";", and add at beginning the "\" character; for example, using the code "" would be "\xf118".

And that's all. Using the Font Awesome icons in our PDF, we can create awesome documents, with no distortion problems and clear image. taking advantage of its vector nature.

Comments

Popular posts from this blog

ASP.NET Boilerplate: an alternative guide to integrate Swagger

Swagger is an excellent tool for API exploration of our RESTful APIs. In this post, we'll cover how to integrate and setup Swagger in an  ASP.NET Boilerplate (ABP) application (with ASP.NET MVC 5.x framework), to provide client-side documentation of its ABP application services. Most of all, this is an alternative documentation to the proposed in its official web site.