We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

We need to highlight some specific words in a document based on a search criteria entered by the user

Hi All,

We are evaluating and already using Aspose to some situations (We are going to buy aspose soon!!!) and now we had another necessity that we would like to solve with aspose.

We need to highlight some specific words in a document based on a search criteria entered by the user. We could do that in a paraghaph basis, using de Run class of the aspose component, bug we did not find a way to get and format specifi words in this “Run”.

Could you help us on this?

This message was posted using Email2Forum by alexey.noskov.

Thanks for your interesting inquiry. I think that you can use ReplaceEvaluator to achieve this. Also you should split your runs and then highlight it. See the following code example.

public void TestHighlightText_283()
    // open document
    Document doc = new Document(@"283_mail_farley.niehues@neomind.com.br\in.doc");
    // create regular expression
    Regex regex = new Regex("test");
    // search text
    doc.Range.Replace(regex, new ReplaceEvaluator(ReplaceAction_283), true);
    // save processed document
ReplaceAction ReplaceAction_283(object sender, ReplaceEvaluatorArgs e)
    // split text of the match node
    string[] arr = (e.MatchNode as Run).Text.Split(new string[] { e.Match.Value }, StringSplitOptions.RemoveEmptyEntries);
    // create empty array list
    ArrayList list = new ArrayList();
    // if match node begins with searched text
    if ((e.MatchNode as Run).Text.StartsWith(e.Match.Value))
        Run run = new Run(e.MatchNode.Document);
        run.Font.HighlightColor = Color.Yellow; //highlight text
        run.Text = e.Match.Value;
    // add athr text
    for (int i = 0; i < arr.Length; i++)
        Run run = new Run(e.MatchNode.Document);
        run.Text = arr[i];
        if (((e.MatchNode as Run).Text.EndsWith((e.Match.Value)) && i == arr.Length - 1) || i < arr.Length - 1)
            Run run1 = new Run(e.MatchNode.Document);
            run1.Font.HighlightColor = Color.Yellow;
            run1.Text = e.Match.Value;
    // add created runs into the document
    foreach (Run run in list)
        (e.MatchNode as Run).ParentParagraph.InsertBefore(run, e.MatchNode);
    // remove old run
    (e.MatchNode as Run).ParentParagraph.ChildNodes.Remove(e.MatchNode);
    return ReplaceAction.Skip;

I hope that it will help you.
Best regards.