如何使用iTextSharp设置PDF段落的字体?

试着按照这里的例子,我添加了以下代码来创建PDF文档的标题:

using (var doc = new Document(PageSize.A4, 50, 50, 25, 25)) { using (var writer = PdfWriter.GetInstance(doc, ms)) { doc.Open(); var docTitle = new Paragraph("UCSC Direct - Direct Payment Form"); var titleFont = FontFactory.GetFont("Lucida Sans", 18, Font.Bold); doc.Add(docTitle); 

但是,创建titleFont的尝试不会编译(“ ‘iTextSharp.text.FontFactory.GetFont(string,float,iTextSharp.text.BaseColor)’的最佳重载方法匹配’有一些无效的参数 ”),所以我让intellisenseless通过一次添加一个arg来“帮助”我。 因为对于第一个arg它说它是字体名称,一个字符串,我添加了“Segoe UI”; 下一个arg是字体大小,一个浮点数,所以我加了18.0; 最后,它调用了字体颜色,一个BaseColor类型,所以我添加了BaseColor.Black,最后得到:

 var titleFont = FontFactory.GetFont("Segoe UI", 18.0, BaseColor.BLACK); 

…但是也不会编译,说“ ‘iTextSharp.text.FontFactory.GetFont(string,string,bool)’的最佳重载方法匹配’有一些无效的参数

因此,当我复制示例并使用string,int和Font样式时,它说不,它需要string,float和BaseColor。 当我添加这些参数时,它改变了它的“思想”,并说它真正想要的是字符串,字符串和布尔?

此外,该示例显示然后将段落添加到文档中,如下所示:

 doc.Add(docTitle, titleFont); 

…但是,这也不会飞,因为“ 没有重载方法’添加’需要2个参数

如何安抚iTextSharp? 无论我是跳舞还是吟唱挽歌,它都不想玩耍。

UPDATE

好的,这编译:

 var docTitle = new Paragraph("UCSC Direct - Direct Payment Form"); var titleFont = FontFactory.GetFont("Courier", 18, BaseColor.BLACK); docTitle.Font = titleFont; doc.Add(docTitle); 

GetFont目前有14种可能的重载

 public static Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color) public static Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color, bool cached) public static Font GetFont(string fontname, string encoding, bool embedded, float size, int style) public static Font GetFont(string fontname, string encoding, bool embedded, float size) public static Font GetFont(string fontname, string encoding, bool embedded) public static Font GetFont(string fontname, string encoding, float size, int style, BaseColor color) public static Font GetFont(string fontname, string encoding, float size, int style) public static Font GetFont(string fontname, string encoding, float size) public static Font GetFont(string fontname, string encoding) public static Font GetFont(string fontname, float size, int style, BaseColor color) public static Font GetFont(string fontname, float size, BaseColor color) public static Font GetFont(string fontname, float size, int style) public static Font GetFont(string fontname, float size) public static Font GetFont(string fontname) 

所以第一步,挑选哪一个最适合你。

以下行不起作用的原因:

 FontFactory.GetFont("Segoe UI", 18.0, BaseColor.BLACK); 

如果因为根据c#规范 ,没有后缀, 18.0被解释为double,因为没有重载.Net是将其转换为字符串的字符串。

 FontFactory.GetFont("Segoe UI", 18.0f, BaseColor.BLACK) 

至于段落本身,您既可以在构造函数中设置字体,也可以只设置段落的Font属性。

 var p1 = new Paragraph("Hello", myFont); var p2 = new Paragraph(); p2.Font = myFont; p2.Add("Hello")