ReplaceTextFmt2.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.Drawing
  6. Imports System.Text
  7. Imports System.Linq
  8. Imports System.Collections.Generic
  9. Imports System.Text.RegularExpressions
  10. Imports GrapeCity.Documents.Word
  11.  
  12. '' This sample loads an existing document, finds all occurrences
  13. '' of a certain string in it, And replaces that string with another one,
  14. '' also changing the character format of the replacement string.
  15. '' This sample Is almost identical to ReplaceTextFmt
  16. '' but uses PersistentRange instead of Range.
  17. '' Its primary purpose Is to illustrate the differences between
  18. '' Range And PersistentRange.
  19. Public Class ReplaceTextFmt2
  20. 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.  
  28. Dim doc = New GcWordDocument()
  29. doc.Load(path)
  30.  
  31. Dim runs = doc.Body.Runs
  32. Dim runRanges = New List(Of PersistentRange)(runs.Count)
  33. For Each run In runs
  34. runRanges.Add(run.GetPersistentRange())
  35. Next
  36.  
  37. For Each rr In runRanges
  38. Dim str = rr.Text
  39. Dim matches = Regex.Matches(str, tFind, RegexOptions.IgnoreCase)
  40. If matches.Count = 0 Then
  41. Continue For
  42. End If
  43.  
  44. Dim color = rr.ParentRun.Font.Color.RGB
  45. rr.Clear()
  46. Dim pos = 0
  47. For Each m In matches
  48. rr.Runs.Add(str.Substring(pos, m.Index - pos)).Font.Color.RGB = color
  49. rr.Runs.Add(tRepl).Font.Color.RGB = Color.Red
  50. pos = m.Index + m.Length
  51. Next
  52. rr.Runs.Add(str.Substring(pos)).Font.Color.RGB = color
  53.  
  54. If Not String.IsNullOrEmpty(rr.Runs.First.GetRange().Text) Then
  55. Throw New Exception("Unexpected")
  56. End If
  57. rr.Runs.First.Delete()
  58.  
  59. '' PersistentRange Is kept up to date when the document changes,
  60. '' so it should be disposed when no longer needed to improve
  61. '' performance And reduce memory consumption:
  62. rr.Dispose()
  63. Next
  64. '' Not strictky necessary but a good practice:
  65. runRanges.Clear()
  66.  
  67. '' Add a note at the end of the document
  68. doc.Body.Sections.Last.GetRange().Paragraphs.Add(
  69. $"DsWord replaced '{tFind}' with '{tRepl}' on {Util.TimeNow():R}.")
  70.  
  71. '' Done
  72. Return doc
  73. End Function
  74. End Class
  75.