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