CharacterFormatting.vb
  1. ''
  2. '' This code is part of Document Solutions for Word demos.
  3. '' Copyright (c) MESCIUS inc. All rights reserved.
  4. ''
  5. Imports GrapeCity.Documents.Word
  6.  
  7. '' This short sample demonstrates the basics of accessing text content
  8. '' and character formatting in DsWord.
  9. '' It creates a document and adds a paragraph of text to it.
  10. '' It then splits the paragraph into two runs, And assigns different
  11. '' font styles to the two halves of the text.
  12. Public Class CharacterFormatting
  13. Function CreateDocx() As GcWordDocument
  14. '' Get a sample paragraph of text
  15. Dim lorem = LoremIpsumPar()
  16. Dim doc = New GcWordDocument()
  17. '' Add the paragraph to the document
  18. Dim p = doc.Body.Paragraphs.Add(lorem)
  19. '' The primary way of manipulating objects in DsWord Is via ranges.
  20. '' Get the range on the paragraph that we've just added:
  21. Dim r = p.GetRange()
  22. '' A Run Is a contiguous fragment of a document with uniform formatting.
  23. '' In our case, we have only one run so far, get it
  24. Dim Run = r.Runs.First
  25. '' Set the size of the font on the whole run
  26. Run.Font.Size = 16
  27. '' A Text represents a contiguous fragment of text. It also belongs to a Run,
  28. '' And cannot span multiple runs (a run though can contain several Text's).
  29. '' Get the text object
  30. Dim Text = Run.GetRange().Texts.First
  31. '' Split the text into two halves (Split() returns the 2nd part)
  32. Dim tIpsum = Text.Split(lorem.Length / 2)
  33. '' At this point, our run contains two Texts (two halves of the original text).
  34. '' We now split the run into two corresponding runs so that we can
  35. '' apply different formatting to the two texts
  36. Dim rIpsum = Run.Split(tIpsum, InsertLocation.Before)
  37. '' The 'text' was split into two halves, but the first half can still
  38. '' be accessed via the 'text' variable.
  39. '' A text's containing run can always be accessed via ParentRun.
  40. '' We set the font of the first half to italic
  41. Text.ParentRun.Font.Italic = True
  42. '' And the font of the second half to bold
  43. rIpsum.Font.Bold = True
  44. '' Done
  45. Return doc
  46. End Function
  47. End Class
  48.