ReplaceTextOld.cs
- //
- // This code is part of Document Solutions for Word demos.
- // Copyright (c) MESCIUS inc. All rights reserved.
- //
- using System;
- using System.IO;
- using System.Drawing;
- using System.Text;
- using System.Text.RegularExpressions;
- using GrapeCity.Documents.Word;
-
- namespace DsWordWeb.Demos
- {
- // NOTE: this sample is obsolete, use the RangeBase.Replace()
- // extension method instead (see ReplaceText).
- //
- // This sample loads an existing document, finds all occurrences
- // of a certain string in it, and replaces that string with another one.
- // Note that this code only finds occurrences of the search string
- // that are completely within a single run. To find strings spanning
- // two or more runs (e.g. if different parts of the string have
- // different formatting) will require a more complex searching logic.
- // For a similar sample that also changes the formatting of the
- // replacement, see ReplaceTextFmt.
- public class ReplaceTextOld
- {
- 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";
-
- var doc = new GcWordDocument();
- doc.Load(path);
-
- // Loop over all texts in the document body:
- foreach (var text in doc.Body.Texts)
- {
- if (text is Break)
- continue;
-
- var str = text.Value;
- var matches = Regex.Matches(str, tFind, RegexOptions.IgnoreCase);
- if (matches.Count == 0)
- continue;
-
- var sb = new StringBuilder();
- var pos = 0;
- foreach (Match m in matches)
- {
- sb.Append(str.Substring(pos, m.Index - pos));
- sb.Append(tRepl);
- pos = m.Index + m.Length;
- }
- sb.Append(str.Substring(pos));
- text.Value = sb.ToString();
- }
- // Add a note at the end of the document:
- doc.Body.Sections.Last.GetRange().Paragraphs.Add(
- $"DsWord replaced '{tFind}' with '{tRepl}' on {DateTime.Now}.");
-
- // Done:
- return doc;
- }
- }
- }
-