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