ReplaceTextFmt.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. // This sample shows how to replace all occurrences of a string
  17. // in a DOCX document (see JsFrameworkExcerpt) using the
  18. // RangeBase.Replace extension method provided by the
  19. // RangeBaseFindReplaceExtensions class.
  20. // This sample is similar to ReplaceText, with the addition of
  21. // also updating the replacement's style.
  22. public class ReplaceTextFmt
  23. {
  24. public GcWordDocument CreateDocx()
  25. {
  26. // The document to replace text in:
  27. var path = Path.Combine("Resources", "WordDocs", "JsFrameworkExcerpt.docx");
  28. // The text to find:
  29. const string tFind = "javascript";
  30. // The replacement:
  31. const string tRepl = "ArabicaScroll";
  32. // Name for the replacement's style:
  33. const string styleName = "my new style";
  34.  
  35. // Load the source document:
  36. var doc = new GcWordDocument();
  37. doc.Load(path);
  38.  
  39. // The new style for replaced text:
  40. var style = doc.Styles.Add(styleName, StyleType.Character);
  41. style.Font.Color.RGB = Color.Red;
  42.  
  43. // Replace text and replacements' style:
  44. var nreplacements = doc.Body.Replace(tFind, tRepl,
  45. new FindReplaceOptions(doc)
  46. {
  47. IgnoreCase = true,
  48. ReplacedCallback = (args_) => args_.ReplacedRange.Runs.ToList().ForEach(r_ => r_.Style = style)
  49. });
  50.  
  51. // Add a note at the end of the document:
  52. doc.Body.Sections.Last.GetRange().Paragraphs.Add(
  53. $"DsWord replaced {nreplacements} occurrences of '{tFind}' with '{tRepl}' on {Util.TimeNow():R}.");
  54.  
  55. // Done:
  56. return doc;
  57. }
  58. }
  59. }
  60.