ReplaceTextFmtOld.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. using Range = GrapeCity.Documents.Word.Range;
  14.  
  15. namespace DsWordWeb.Demos
  16. {
  17. // NOTE: this sample is obsolete, use the RangeBase.Replace()
  18. // extension method instead (see ReplaceTextFmt).
  19. //
  20. // This sample loads an existing document, finds all occurrences
  21. // of a certain string in it, and replaces that string with another one,
  22. // also changing the character format of the replacement string.
  23. // This sample is similar to ReplaceText, with the addition of
  24. // formatting change, and has the same limitation - it only finds
  25. // occurrences of the search string that are completely within a single run.
  26. // See ReplaceTextFmt2 for an example of using PersistentRange in the
  27. // same scenario.
  28. public class ReplaceTextFmtOld
  29. {
  30. public GcWordDocument CreateDocx()
  31. {
  32. // The document to replace text in:
  33. var path = Path.Combine("Resources", "WordDocs", "JsFrameworkExcerpt.docx");
  34. // The text to find:
  35. const string tFind = "javascript";
  36. // The replacement:
  37. const string tRepl = "ArabicaScroll";
  38.  
  39. var doc = new GcWordDocument();
  40. doc.Load(path);
  41.  
  42. var runs = doc.Body.Runs;
  43. List<Range> runRanges = new List<Range>(runs.Count);
  44. foreach (var run in runs)
  45. runRanges.Add(run.GetRange());
  46.  
  47. foreach (var rr in runRanges)
  48. {
  49. var str = rr.Text;
  50. var matches = Regex.Matches(str, tFind, RegexOptions.IgnoreCase);
  51. if (matches.Count == 0)
  52. continue;
  53.  
  54. var color = rr.ParentRun.Font.Color.RGB;
  55. rr.Clear();
  56. var r = rr.Runs.Last;
  57. var pos = 0;
  58. foreach (Match m in matches)
  59. {
  60. r = r.GetRange().Runs.Insert(str.Substring(pos, m.Index - pos), InsertLocation.After);
  61. r.Font.Color.RGB = color;
  62. r = r.GetRange().Runs.Insert(tRepl, InsertLocation.After);
  63. r.Font.Color.RGB = Color.Red;
  64. pos = m.Index + m.Length;
  65. }
  66. r = r.GetRange().Runs.Insert(str.Substring(pos), InsertLocation.After);
  67. r.Font.Color.RGB = color;
  68. if (!string.IsNullOrEmpty(rr.Runs.First.GetRange().Text))
  69. throw new Exception("Unexpected");
  70. rr.Runs.First.Delete();
  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.