简体   繁体   中英

Unable to use custom font in iText7 Visual Studio

I'm creating an application on Visual Studio and have added in a function that creates a PDF on button click event using iText7. I'm using a custom font that is in my resources and it works fine using the path "../../Resources.[FontName].ttf" when debugging through visual studio but when I run the application file I get an error saying that the resource or file cannot be found . I assume it is because the file is stored in the.resx file and isn't accessible through the path (shown above) outside of visual studio. What path can I use to access the font file so that it works outside of visual studio through the delivered application?

I thought I would share the solution I used for my own problem in case anyone stumbles over the same issue.

It is rather simple. I added the font.ttf file into my resources. It must be stored as a byte[] file. So go to your Resources.Designer.cs file and make sure it looks something like this:

internal static byte[] BebasNeueRegular {
        get {
            object obj = ResourceManager.GetObject("BebasNeueRegular", resourceCulture);
            return ((byte[])(obj));
        }
    }

Then in your class where you are creating the PDF, set your font using iText's PdfFontFactory :

PdfFont font = PdfFontFactory.CreateFont(Properties.Resources.BebasNeueRegular, true);
doc.SetFont(font);

You can use PdfFontFactory.CreateFont method to load the font file.

Here is a code example you can refer to.

    PdfFont font = PdfFontFactory.CreateFont("E:\\AmaticSC-Regular.ttf");
    PdfWriter writer = new PdfWriter("E:\\demo.pdf");
    PdfDocument pdf = new PdfDocument(writer);
    Document document = new Document(pdf);
    Paragraph header = new Paragraph("HEADER").SetFont(font).SetFontSize(50);

    document.Add(header);
    document.Close();

Result:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM