在iTextSharp中使用富文本值进行粗体扩展 [英] Bolding with Rich Text Values in iTextSharp

查看:293
本文介绍了在iTextSharp中使用富文本值进行粗体扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用iTextSharp在句子中加粗单个单词?我正在处理来自xml的大段文本,我试图加粗几个单词,而不必将字符串分成单个短语。

Is it possible to bold a single word within a sentence with iTextSharp? I'm working with large paragraphs of text coming from xml, and I am trying to bold several individual words without having to break the string into individual phrases.

例如:

document.Add(new Paragraph("this is <b>bold</b> text"));

应该输出......

should output...

这个是粗体文本

推荐答案

正如@kuujinbo指出的那样, XMLWorker 对象,这是大多数新的HTML解析工作正在进行的地方。但是,如果您只是使用粗体或斜体等简单命令,则可以使用本机 iTextSharp.text.html.simpleparser.HTMLWorker 类。您可以将其包装到辅助方法中,例如:

As @kuujinbo pointed out there is the XMLWorker object which is where most of the new HTML parsing work is being done. But if you've just got simple commands like bold or italic you can use the native iTextSharp.text.html.simpleparser.HTMLWorker class. You could wrap it into a helper method such as:

private Paragraph CreateSimpleHtmlParagraph(String text) {
    //Our return object
    Paragraph p = new Paragraph();

    //ParseToList requires a StreamReader instead of just text
    using (StringReader sr = new StringReader(text)) {
        //Parse and get a collection of elements
        List<IElement> elements = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(sr, null);
        foreach (IElement e in elements) {
            //Add those elements to the paragraph
            p.Add(e);
        }
    }
    //Return the paragraph
    return p;
}

然后代替此:

document.Add(new Paragraph("this is <b>bold</b> text"));

你可以使用这个:

document.Add(CreateSimpleHtmlParagraph("this is <b>bold</b> text"));
document.Add(CreateSimpleHtmlParagraph("this is <i>italic</i> text"));
document.Add(CreateSimpleHtmlParagraph("this is <b><i>bold and italic</i></b> text"));

这篇关于在iTextSharp中使用富文本值进行粗体扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆