SplitDocs.vb
''
'' This code is part of Document Solutions for Word demos.
'' Copyright (c) MESCIUS inc. All rights reserved.
''
Imports System.IO
Imports System.Drawing
Imports System.Linq
Imports GrapeCity.Documents.Word

'' 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 Function CreateDocx() As GcWordDocument
        '' The document will be split before the paragraph beginning with
        Const p2start = "This is the second paragraph of the original document"

        Dim doc = New GcWordDocument()
        doc.Load(Path.Combine("Resources", "WordDocs", "SampleParagraphs.docx"))

        Dim rng0 As RangeBase = Nothing, rng1 As RangeBase = Nothing
        For Each p In doc.Body.Paragraphs
            If p.GetRange().Text.StartsWith(p2start) Then
                rng0 = doc.Body.GetPersistentRange(doc.Body.Start, p.Previous.End)
                rng1 = doc.Body.GetPersistentRange(p.Start, doc.Body.End)
                Exit For
            End If
        Next

        If rng0 Is Nothing OrElse rng1 Is Nothing Then
            Throw New Exception("Unexpected: could not find the split point.")
        End If

        Dim docs = doc.SplitDocument(rng0, rng1)
        If docs.Count() <> 2 Then
            Throw New Exception("Unexpected: the split should have returned 2 documents.")
        End If

        '' Return the 2nd of the two documents (the one starting with 'p2start':
        Return docs.Last()
    End Function
End Class