Loading BaseFont from embedded resource in iTextSharp

為{幸葍}努か 提交于 2019-12-12 12:26:52

问题


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?


回答1:


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[].




回答2:


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.




回答3:


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);


来源:https://stackoverflow.com/questions/8782022/loading-basefont-from-embedded-resource-in-itextsharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!