使用itextsharp更改pdf中的默认字体和fontsize

时间:2013-12-10 06:55:41

标签: itextsharp

如何使用iIextSharp为PDF文档设置默认字体和字体大小,以便在整个PDF中使用它。

4 个答案:

答案 0 :(得分:3)

与俄语和罗马尼亚字母(itextsharp 5.5.6.0, .net 3.5)遇到同样的问题。我刚补充说:

string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");
FontFactory.Register(arialuniTff);    
StyleSheet ST = new StyleSheet();
ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.FACE, "Arial Unicode MS");
ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H)

parser.SetStyleSheet(ST);

但在开始解析TextReader之前添加:

parser.Parse(reader);

否则它将无效。

答案 1 :(得分:2)

使用以下功能(您可以根据需要更改字体样式/大小)

Private Function FormatPhrase(value As String) As Phrase
    Return New Phrase(value, FontFactory.GetFont(FontFactory.HELVETICA, 8))
End Function

并使用它来显示信息。例如,

Dim stuName As PdfPCell = New PdfPCell(FormatPhrase("Sample Document"))

答案 2 :(得分:1)

感谢答案的人,但我通过从外部CSS获取字体来覆盖XmlWorker的默认字体来解决问题:

public static void ParseHtmlToPdf(IElementHandler handler,StringReader inputText,float maxWidth,float maxHeight)
    {
        XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider();
        fontProvider.Register(HttpContext.Current.Server.MapPath(@"~/Content/IMTLayout/IMTFonts/CenturyGothic/GOTHIC.TTF"), "Default_CenturyGothic");
        CssAppliers ca = new CssAppliersImpl(fontProvider);
        var context = new HtmlPipelineContext(ca);
        context.SetAcceptUnknown(true);
        context.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

        context.SetImageProvider(new CustomImageHandler { BaseUri = HttpContext.Current.Request.Url.ToString(),MaxHeight = maxHeight,MaxWidth = maxWidth});
        var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
        cssResolver.AddCssFile(HttpContext.Current.Server.MapPath("~/Content/IMTLayout/IMTCss/pdfreport.css"), true);
        var pipeline = new CssResolverPipeline(cssResolver,
                                               new HtmlPipeline(context, new ElementHandlerPipeline(handler, null)));
        var worker = new XMLWorker(pipeline, true);
        var parser = new XMLParser();
        parser.AddListener(worker);
        parser.Parse(inputText);
    }

我的CSS文件具有以下属性:

strong b {font-weight:bold;font-family:Century Gothic;}
em i {font-style:italic;font-family:Century Gothic;}
p,ol,ul,li,dl,a,td,tr{font-family:Century Gothic;font-size:10pt;color:#191919;}
a{color:Blue;}
td,tr,table{border-width:0.5px;}

答案 3 :(得分:0)

试试这个:

BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);


Paragraph p1 = new Paragraph(new Chunk("Some text content here \n", font));