Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bolding with Rich Text Values in iTextSharp

Tags:

itextsharp

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.

Eg:

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

should output...

this is bold text

like image 292
Justin Ploof Avatar asked Dec 12 '22 07:12

Justin Ploof


2 Answers

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

Then instead of this:

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

You could use this:

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"));
like image 138
Chris Haas Avatar answered Jan 21 '23 11:01

Chris Haas


I know that this is an old question, but I could not get the other examples here to work for me. But adding the text in Chucks with different fonts did.

//define a bold font to be used
Font boldFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12);

//add a phrase and add Chucks to it
var phrase2 = new Phrase();
phrase2.Add(new Chunk("this is "));
phrase2.Add(new Chunk("bold", boldFont));
phrase2.Add(new Chunk(" text"));

document.Add(phrase2);

enter image description here

like image 38
wruckie Avatar answered Jan 21 '23 11:01

wruckie