2012-01-08 33 views
2

我正在使用iTextSharp生成動態PDF文檔。我有一個要求使用一個非常特定的字體,我有許可的.ttf文件。從iTextSharp中的嵌入式資源中加載BaseFont

我可以使用下面的代碼來加載和使用字體,但我更喜歡將字體文件定位爲嵌入式資源,而不是依賴磁盤上的特定位置。

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

任何人都可以幫助我如何實現這一目標嗎?

public static BaseFont CreateFont(String name, String encoding, bool embedded, bool cached, byte[] ttfAfm, byte[] pfb) 

ttfAfm應該代表TTF:

+0

結帳此鏈接iTextSharp的站點http://www.mikesdotnetting.com/Article/81/iTextSharp-Working-with-Fonts – MethodMan 2012-01-08 23:19:05

+3

@DJKRAZE資源文件 - 你引用的網站中的哪個地方討論了從嵌入式資源中加載字體? – 2012-01-08 23:22:53

回答

9

審查它看起來像您可以使用的BaseFont.CreateFont以下過載使用您的嵌入式資源作爲字體(從BaseFont.cs線543)的iTextSharp的源之後文件爲byte[]

+2

+1 - 如果您還不知道[API位於此處](http://api.itextpdf.com/itext/),並且[BaseFont文檔位於此處](http://api.itextpdf.com /itext/com/itextpdf/text/pdf/BaseFont.html)。在Java中,但要麼在.NET中相同,要麼足夠接近以找出結果。或者如果你喜歡*看着源代碼,無視;) – kuujinbo 2012-01-09 07:07:15

+0

感謝您的指導,我設法讓代碼工作,我已經在下面發佈。 – bigtv 2012-01-09 21:31:40

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

我還發現,不設置字體的名稱(CreatFont的第一個參數())拋出一個不起眼的異常,但指定的確切名稱字體文件工作得很好。

2

您可以直接從資源中獲取fontBytes。在下面的例子我有一個名爲「FontFiles.resx」

var customFont = BaseFont.CreateFont("fontfilename.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, BaseFont.CACHED, FontFiles.fontfilename, null);