ReplaceTextOld.cs
  1. //
  2. // This code is part of Document Solutions for Word demos.
  3. // Copyright (c) MESCIUS inc. All rights reserved.
  4. //
  5. using System;
  6. using System.IO;
  7. using System.Drawing;
  8. using System.Text;
  9. using System.Text.RegularExpressions;
  10. using GrapeCity.Documents.Word;
  11.  
  12. namespace DsWordWeb.Demos
  13. {
  14. // NOTE: this sample is obsolete, use the RangeBase.Replace()
  15. // extension method instead (see ReplaceText).
  16. //
  17. // This sample loads an existing document, finds all occurrences
  18. // of a certain string in it, and replaces that string with another one.
  19. // Note that this code only finds occurrences of the search string
  20. // that are completely within a single run. To find strings spanning
  21. // two or more runs (e.g. if different parts of the string have
  22. // different formatting) will require a more complex searching logic.
  23. // For a similar sample that also changes the formatting of the
  24. // replacement, see ReplaceTextFmt.
  25. public class ReplaceTextOld
  26. {
  27. public GcWordDocument CreateDocx()
  28. {
  29. // The document to replace text in:
  30. var path = Path.Combine("Resources", "WordDocs", "JsFrameworkExcerpt.docx");
  31. // The text to find:
  32. const string tFind = "javascript";
  33. // The replacement:
  34. const string tRepl = "ArabicaScroll";
  35.  
  36. var doc = new GcWordDocument();
  37. doc.Load(path);
  38.  
  39. // Loop over all texts in the document body:
  40. foreach (var text in doc.Body.Texts)
  41. {
  42. if (text is Break)
  43. continue;
  44.  
  45. var str = text.Value;
  46. var matches = Regex.Matches(str, tFind, RegexOptions.IgnoreCase);
  47. if (matches.Count == 0)
  48. continue;
  49.  
  50. var sb = new StringBuilder();
  51. var pos = 0;
  52. foreach (Match m in matches)
  53. {
  54. sb.Append(str.Substring(pos, m.Index - pos));
  55. sb.Append(tRepl);
  56. pos = m.Index + m.Length;
  57. }
  58. sb.Append(str.Substring(pos));
  59. text.Value = sb.ToString();
  60. }
  61. // Add a note at the end of the document:
  62. doc.Body.Sections.Last.GetRange().Paragraphs.Add(
  63. $"DsWord replaced '{tFind}' with '{tRepl}' on {DateTime.Now}.");
  64.  
  65. // Done:
  66. return doc;
  67. }
  68. }
  69. }
  70.