ReplaceTextOld.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.Text.RegularExpressions
  9. Imports GrapeCity.Documents.Word
  10.  
  11. '' NOTE: this sample is obsolete, use the RangeBase.Replace()
  12. '' @extension method instead (see @{ReplaceText}).
  13. ''
  14. '' This sample loads an existing document, finds all occurrences
  15. '' of a certain string in it, And replaces that string with another one.
  16. '' Note that this code only finds occurrences of the search string
  17. '' that are completely within a single run. To find strings spanning
  18. '' two Or more runs (e.g. if different parts of the string have
  19. '' different formatting) will require a more complex searching logic.
  20. '' For a similar sample that also changes the formatting of the
  21. '' replacement, see ReplaceTextFmt.
  22. Public Class ReplaceTextOld
  23. Public Function CreateDocx() As GcWordDocument
  24. '' The document to replace text in:
  25. Dim path = System.IO.Path.Combine("Resources", "WordDocs", "JsFrameworkExcerpt.docx")
  26. '' The text to find
  27. Const tFind = "javascript"
  28. '' The replacement
  29. Const tRepl = "ArabicaScroll"
  30.  
  31. Dim doc = New GcWordDocument()
  32. doc.Load(path)
  33.  
  34. '' Loop over all texts in the document body
  35. For Each text In doc.Body.Texts
  36. If TypeOf (text) Is Break Then
  37. Continue For
  38. End If
  39.  
  40. Dim str = text.Value
  41. Dim matches = Regex.Matches(str, tFind, RegexOptions.IgnoreCase)
  42. If matches.Count = 0 Then
  43. Continue For
  44. End If
  45.  
  46. Dim sb = New StringBuilder()
  47. Dim pos = 0
  48. For Each m In matches
  49. sb.Append(str.Substring(pos, m.Index - pos))
  50. sb.Append(tRepl)
  51. pos = m.Index + m.Length
  52. Next
  53. sb.Append(str.Substring(pos))
  54. text.Value = sb.ToString()
  55. Next
  56.  
  57. '' Add a note at the end of the document:
  58. doc.Body.Sections.Last.GetRange().Paragraphs.Add(
  59. $"DsWord replaced '{tFind}' with '{tRepl}' on {Util.TimeNow():R}.")
  60.  
  61. '' Done
  62. Return doc
  63. End Function
  64. End Class
  65.