ReplaceTextFmtOld.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 similar to ReplaceText, with the addition of
  16. '' formatting change, And has the same limitation - it only finds
  17. '' occurrences of the search string that are completely within a single run.
  18. '' See ReplaceTextFmt2 for an example of using PersistentRange in the
  19. '' same scenario.
  20. Public Class ReplaceTextFmtOld
  21. Function CreateDocx() As GcWordDocument
  22. '' The document to replace text in:
  23. Dim path = IO.Path.Combine("Resources", "WordDocs", "JsFrameworkExcerpt.docx")
  24. '' The text to find
  25. Const tFind = "javascript"
  26. '' The replacement
  27. Const tRepl = "ArabicaScroll"
  28.  
  29. Dim doc = New GcWordDocument()
  30. doc.Load(path)
  31.  
  32. Dim runs = doc.Body.Runs
  33. Dim runRanges = New List(Of Range)(runs.Count)
  34. For Each run In runs
  35. runRanges.Add(run.GetRange())
  36. Next
  37.  
  38. For Each rr In runRanges
  39. Dim str = rr.Text
  40. Dim matches = Regex.Matches(str, tFind, RegexOptions.IgnoreCase)
  41. If matches.Count = 0 Then
  42. Continue For
  43. End If
  44.  
  45. Dim color = rr.ParentRun.Font.Color.RGB
  46. rr.Clear()
  47. Dim r = rr.Runs.Last
  48. Dim pos = 0
  49. For Each m In matches
  50. r = r.GetRange().Runs.Insert(str.Substring(pos, m.Index - pos), InsertLocation.After)
  51. r.Font.Color.RGB = color
  52. r = r.GetRange().Runs.Insert(tRepl, InsertLocation.After)
  53. r.Font.Color.RGB = Color.Red
  54. pos = m.Index + m.Length
  55. Next
  56. r = r.GetRange().Runs.Insert(str.Substring(pos), InsertLocation.After)
  57. r.Font.Color.RGB = color
  58. If Not String.IsNullOrEmpty(rr.Runs.First.GetRange().Text) Then
  59. Throw New Exception("Unexpected")
  60. End If
  61. rr.Runs.First.Delete()
  62. Next
  63. '' Not strictly necessary but a good practice:
  64. runRanges.Clear()
  65.  
  66. '' Add a note at the end of the document
  67. doc.Body.Sections.Last.GetRange().Paragraphs.Add(
  68. $"DsWord replaced '{tFind}' with '{tRepl}' on {Util.TimeNow():R}.")
  69.  
  70. '' Done
  71. Return doc
  72. End Function
  73. End Class
  74.