SplitDocs.cs
//
// This code is part of Document Solutions for Word demos.
// Copyright (c) MESCIUS inc. All rights reserved.
//
using System;
using System.IO;
using System.Drawing;
using System.Linq;
using GrapeCity.Documents.Word;
using Range = GrapeCity.Documents.Word.Range;

namespace DsWordWeb.Demos
{
    // This sample shows how to split a DOCX into several documents.
    // To see see the original document, run the SampleParagraphs sample.
    public class SplitDocs
    {
        public GcWordDocument CreateDocx()
        {
            // The document will be split before the paragraph beginning with:
            const string p2start = "This is the second paragraph of the original document";

            var doc = new GcWordDocument();
            doc.Load(Path.Combine("Resources", "WordDocs", "SampleParagraphs.docx"));

            Range rng0 = null, rng1 = null;
            foreach (var p in doc.Body.Paragraphs)
                if (p.GetRange().Text.StartsWith(p2start))
                {
                    rng0 = doc.Body.GetPersistentRange(doc.Body.Start, p.Previous.End);
                    rng1 = doc.Body.GetPersistentRange(p.Start, doc.Body.End);
                    break;
                }

            if (rng0 == null || rng1 == null)
                throw new Exception("Unexpected: could not find the split point.");

            var docs = doc.SplitDocument(rng0, rng1);
            if (docs.Count() != 2)
                throw new Exception("Unexpected: the split should have returned 2 documents.");

            // Return the 2nd of the two documents (the one starting with 'p2start':
            return docs.Last();
        }
    }
}