ReplaceTextFmt2.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.Linq;
  10. using System.Collections.Generic;
  11. using System.Text.RegularExpressions;
  12. using GrapeCity.Documents.Word;
  13.  
  14. namespace DsWordWeb.Demos
  15. {
  16. // NOTE: this sample is obsolete, use the RangeBase.Replace()
  17. // extension method instead (see ReplaceTextFmt).
  18. //
  19. // This sample loads an existing document, finds all occurrences
  20. // of a certain string in it, and replaces that string with another one,
  21. // also changing the character format of the replacement string.
  22. // This sample is almost identical to ReplaceTextFmt
  23. // but uses PersistentRange instead of Range.
  24. // Its primary purpose is to illustrate the differences between
  25. // Range and PersistentRange.
  26. public class ReplaceTextFmt2
  27. {
  28. public GcWordDocument CreateDocx()
  29. {
  30. // The document to replace text in:
  31. var path = Path.Combine("Resources", "WordDocs", "JsFrameworkExcerpt.docx");
  32. // The text to find:
  33. const string tFind = "javascript";
  34. // The replacement:
  35. const string tRepl = "ArabicaScroll";
  36.  
  37. var doc = new GcWordDocument();
  38. doc.Load(path);
  39.  
  40. var runs = doc.Body.Runs;
  41. List<PersistentRange> runRanges = new List<PersistentRange>(runs.Count);
  42. foreach (var run in runs)
  43. runRanges.Add(run.GetPersistentRange());
  44.  
  45. foreach (var rr in runRanges)
  46. {
  47. var str = rr.Text;
  48. var matches = Regex.Matches(str, tFind, RegexOptions.IgnoreCase);
  49. if (matches.Count == 0)
  50. continue;
  51.  
  52. var color = rr.ParentRun.Font.Color.RGB;
  53. rr.Clear();
  54. var pos = 0;
  55. foreach (Match m in matches)
  56. {
  57. rr.Runs.Add(str.Substring(pos, m.Index - pos)).Font.Color.RGB = color;
  58. rr.Runs.Add(tRepl).Font.Color.RGB = Color.Red;
  59. pos = m.Index + m.Length;
  60. }
  61. rr.Runs.Add(str.Substring(pos)).Font.Color.RGB = color;
  62.  
  63. if (!string.IsNullOrEmpty(rr.Runs.First.GetRange().Text))
  64. throw new Exception("Unexpected");
  65. rr.Runs.First.Delete();
  66.  
  67. // PersistentRange is kept up to date when the document changes,
  68. // so it should be disposed when no longer needed to improve
  69. // performance and reduce memory consumption:
  70. rr.Dispose();
  71. }
  72. // Not strictky necessary but a good practice:
  73. runRanges.Clear();
  74.  
  75. // Add a note at the end of the document:
  76. doc.Body.Sections.Last.GetRange().Paragraphs.Add(
  77. $"DsWord replaced '{tFind}' with '{tRepl}' on {Util.TimeNow():r)}.");
  78.  
  79. // Done:
  80. return doc;
  81. }
  82. }
  83. }
  84.