Reputation: 2711
I am using iTextSharp to generate dynamic PDF documents. I have a requirement to use a very specific font for which I have the licensed .ttf file.
I can use the code the below to load and use the font, however I would much prefer to have the font file as located as an embedded resource in my class library rather than being reliant on a specific location on disk.
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));
Can anybody help me as to how I might achieve this?
Upvotes: 4
Views: 10824
Reputation: 211
You can get fontBytes directly from resources. In example below I have resource file named "FontFiles.resx"
var customFont = BaseFont.CreateFont("fontfilename.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, BaseFont.CACHED, FontFiles.fontfilename, null);
Upvotes: 2
Reputation: 2711
This is example code on how to do it:
Stream fontStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("font.resource.path.fontfilename.ttf");
var fontBytes = ReadByteArray(fontStream);
var customFont = BaseFont.CreateFont("fontfilename.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, BaseFont.CACHED, fontBytes, null);
I also found that not setting the font name (first param of CreatFont()) threw an obscure exception, but specifying the exact name of the font file worked just fine.
Upvotes: 7
Reputation: 18965
After reviewing the ITextSharp source it looks like you may be able to use the following overload of BaseFont.CreateFont
to use your embedded resource as a font (line 543 from BaseFont.cs):
public static BaseFont CreateFont(String name, String encoding, bool embedded, bool cached, byte[] ttfAfm, byte[] pfb)
ttfAfm
should represent the TTF file as a byte[]
.
Upvotes: 10