ReplaceTextFmt.vb
  1. ''
  2. '' This code is part of Document Solutions for Word demos.
  3. '' Copyright (c) MESCIUS inc. All rights reserved.
  4. ''
  5. Imports System.IO
  6. Imports System.Drawing
  7. Imports System.Text
  8. Imports System.Linq
  9. Imports System.Collections.Generic
  10. Imports System.Text.RegularExpressions
  11. Imports GrapeCity.Documents.Word
  12.  
  13. '' This sample shows how to replace all occurrences of a string
  14. '' in a DOCX document (see JsFrameworkExcerpt) using the
  15. '' RangeBase.Replace extension method provided by the
  16. '' RangeBaseFindReplaceExtensions class.
  17. '' This sample Is similar to ReplaceText, with the addition of
  18. '' also updating the replacement's style.
  19. Public Class ReplaceTextFmt
  20. Public Function CreateDocx() As GcWordDocument
  21. '' The document to replace text in:
  22. Dim path = IO.Path.Combine("Resources", "WordDocs", "JsFrameworkExcerpt.docx")
  23. '' The text to find
  24. Const tFind = "javascript"
  25. '' The replacement
  26. Const tRepl = "ArabicaScroll"
  27. '' Name for the replacement's style:
  28. Const styleName = "my new style"
  29.  
  30. '' Load the source document:
  31. Dim doc = New GcWordDocument()
  32. doc.Load(path)
  33.  
  34. '' The New style for replaced text:
  35. Dim style = doc.Styles.Add(styleName, StyleType.Character)
  36. style.Font.Color.RGB = Color.Red
  37.  
  38. '' Replace text And replacements' style:
  39. Dim nreplacements = doc.Body.Replace(tFind, tRepl,
  40. New FindReplaceOptions(doc) With
  41. {
  42. .IgnoreCase = True,
  43. .ReplacedCallback = Sub(args_) args_.ReplacedRange.Runs.ToList().ForEach(Sub(r_) r_.Style = style)
  44. })
  45.  
  46. '' Add a note at the end of the document
  47. doc.Body.Paragraphs.Add(
  48. $"DsWord replaced {nreplacements} occurrences of '{tFind}' with '{tRepl}' on {Util.TimeNow():R}.")
  49.  
  50. '' Done
  51. Return doc
  52. End Function
  53. End Class
  54.