ReplaceTextFmt.cs
//
// This code is part of GrapeCity Documents for Word samples.
// Copyright (c) GrapeCity, Inc. All rights reserved.
//
using System;
using System.IO;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using GrapeCity.Documents.Word;

namespace GcWordWeb.Samples
{
    // This sample shows how to replace all occurrences of a string
    // in a DOCX document (see JsFrameworkExcerpt) using the
    // RangeBase.Replace extension method provided by the
    // RangeBaseFindReplaceExtensions class.
    // This sample is similar to ReplaceText, with the addition of
    // also updating the replacement's style.
    public class ReplaceTextFmt
    {
        public GcWordDocument CreateDocx()
        {
            // The document to replace text in:
            var path = Path.Combine("Resources", "WordDocs", "JsFrameworkExcerpt.docx");
            // The text to find:
            const string tFind = "javascript";
            // The replacement:
            const string tRepl = "ArabicaScroll";
            // Name for the replacement's style:
            const string styleName = "my new style";

            // Load the source document:
            var doc = new GcWordDocument();
            doc.Load(path);

            // The new style for replaced text:
            var style = doc.Styles.Add(styleName, StyleType.Character);
            style.Font.Color.RGB = Color.Red;

            // Replace text and replacements' style:
            var nreplacements = doc.Body.Replace(tFind, tRepl,
                new FindReplaceOptions(doc)
                {
                    IgnoreCase = true,
                    ReplacedCallback = (args_) => args_.ReplacedRange.Runs.ToList().ForEach(r_ => r_.Style = style)
                });

            // Add a note at the end of the document:
            doc.Body.Sections.Last.GetRange().Paragraphs.Add(
                $"GcWord replaced {nreplacements} occurrences of '{tFind}' with '{tRepl}' on {DateTime.Now}.");

            // Done:
            return doc;
        }
    }
}