SplitDocs.cs
  1. //
  2. // This code is part of Document Solutions for Word demos.
  3. // Copyright (c) MESCIUS inc. All rights reserved.
  4. //
  5. using System;
  6. using System.IO;
  7. using System.Drawing;
  8. using System.Linq;
  9. using GrapeCity.Documents.Word;
  10. using Range = GrapeCity.Documents.Word.Range;
  11.  
  12. namespace DsWordWeb.Demos
  13. {
  14. // This sample shows how to split a DOCX into several documents.
  15. // To see see the original document, run the SampleParagraphs sample.
  16. public class SplitDocs
  17. {
  18. public GcWordDocument CreateDocx()
  19. {
  20. // The document will be split before the paragraph beginning with:
  21. const string p2start = "This is the second paragraph of the original document";
  22.  
  23. var doc = new GcWordDocument();
  24. doc.Load(Path.Combine("Resources", "WordDocs", "SampleParagraphs.docx"));
  25.  
  26. Range rng0 = null, rng1 = null;
  27. foreach (var p in doc.Body.Paragraphs)
  28. if (p.GetRange().Text.StartsWith(p2start))
  29. {
  30. rng0 = doc.Body.GetPersistentRange(doc.Body.Start, p.Previous.End);
  31. rng1 = doc.Body.GetPersistentRange(p.Start, doc.Body.End);
  32. break;
  33. }
  34.  
  35. if (rng0 == null || rng1 == null)
  36. throw new Exception("Unexpected: could not find the split point.");
  37.  
  38. var docs = doc.SplitDocument(rng0, rng1);
  39. if (docs.Count() != 2)
  40. throw new Exception("Unexpected: the split should have returned 2 documents.");
  41.  
  42. // Return the 2nd of the two documents (the one starting with 'p2start':
  43. return docs.Last();
  44. }
  45. }
  46. }
  47.