Changing format of text in a document

Hi,

Looking for some help on chainging the format of specific text in a document. For example, I would like to open a document, find all instances of the word “test” and italicize them. I looked at the search and replace function but it did not have any way to replace a string with formattting (that I could see).

All help is appreciated.

Hi
Thanks for your request. Of course you can achieve this using Replace method. You should use ReplaceEvaluator in this case. Please see the following link for more information.
https://docs.aspose.com/words/net/find-and-replace/
Also see the following code:

public void Test003()
{
    // Open document
    Document doc = new Document(@"Test003\in.doc");
    // Replace word with mergefield using ReplaceEvaluator
    Regex regex = new Regex("word");
    doc.Range.Replace(regex, new ReplaceEvaluator(ReplaceInsertMergeField), false);
    // Save output document
    doc.Save(@"Test003\out.doc");
}
private ReplaceAction ReplaceInsertMergeField(object sender, ReplaceEvaluatorArgs e)
{
    // Get MatchNode
    Run run1 = (Run)e.MatchNode;
    // Create Run
    Run run2 = (Run)run1.Clone(true);
    // Get index of match value
    int index = run1.Text.IndexOf(e.Match.Value);
    // split run that contains matched text 
    run2.Text = run1.Text.Substring(index + e.Match.Value.Length);
    run1.Text = run1.Text.Substring(0, index);
    run1.ParentParagraph.InsertAfter(run2, run1);
    // Create document builder
    DocumentBuilder builder = new DocumentBuilder(e.MatchNode.Document);
    // Move to run2
    builder.MoveTo(run2);
    // Change font
    builder.Font.Bold = true;
    builder.Font.Italic = true;
    // Insert value
    builder.Write(e.Match.Value);
    return ReplaceAction.Skip;
}

Hope this helps.
Best regards.

2 posts were split to a new topic: Change Font Style to Italic in Word Document | C# .NET