从iTextSharp中的嵌入式资源加载BaseFont

big*_*gtv 3 c# asp.net itextsharp

我正在使用iTextSharp生成动态PDF文档.我需要使用我拥有许可的.ttf文件的非常特定的字体.

我可以使用代码下面的加载和使用的字体,但我更希望有字体文件在我的类库位于作为嵌入资源,而不是在磁盘上的一个特定位置的依赖.

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));
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮我解决这个问题吗?

M.B*_*ock 9

在查看ITextSharp源之后,您可能会使用以下重载BaseFont.CreateFont来将嵌入式资源用作字体(来自BaseFont.cs的第543 ):

public static BaseFont CreateFont(String name, String encoding, bool embedded, bool cached, byte[] ttfAfm, byte[] pfb)
Run Code Online (Sandbox Code Playgroud)

ttfAfm应该将TTF文件表示为byte[].

  • +1 - 如果您还不知道[API在这里](http://api.itextpdf.com/itext/),[BaseFont文档在这里](http://api.itextpdf.com/ iText的/ COM/itextpdf /文本/ PDF/BaseFont.html).在Java中,但要么在.NET中相同,要么足够接近.或者,如果您*喜欢*查看源代码,请忽略;) (2认同)

big*_*gtv 5

这是关于如何执行此操作的示例代码:

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);
Run Code Online (Sandbox Code Playgroud)

我还发现没有设置字体名称(CreatFont()的第一个参数)引发了一个模糊的异常,但指定字体文件的确切名称工作得很好.