Reputation: 99
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?
Upvotes: 0
Views: 1497
Reputation: 99
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);
Upvotes: 3
Reputation: 5986
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:
Upvotes: 1