Products
PDFKit.NET 4.0
Created
5/22/2014
Tags
Generate PDF

This code sample shows how to split a PDF document into multiple documents. The splitting is based on the bookmarks in the original PDF document.

The following code will go through all bookmarks in the PDF document and make copies of the bookmarked sections. These copies will be saved as seperate PDF documents. This shows you how you can work with the Bookmark class to get the information you need.

C# code sample BookmarkCollection bookmarks = document.Bookmarks; for (int index = 0, fromPage = 0; index < bookmarks.Count; index++) { // determine last page of next part int toPage = -1; if (index == bookmarks.Count - 1) { // last bookmark - so just append all remaining pages toPage = document.Pages.Count; } else { // not the last bookmark - append up to the page where // the next bookmark points to GoToAction action = bookmarks[index + 1].Actions[0] as GoToAction; if (null != action) { InternalDestination destination = action.Destination as InternalDestination; if (null != destination) { toPage = destination.Page.Index; } } } // create a new part if (-1 != toPage) { Document part = new Document(); foreach (Page p in document.Pages) { part.Pages.Add(p.Clone()); } string title = bookmarks[index].Title; using (FileStream fileOut = new FileStream( string.Format(@"..\..\{0}.pdf", title), FileMode.Create, FileAccess.Write)) { Console.WriteLine("Writing {0} - {1} of {2}", title, index, bookmarks.Count); part.Write(fileOut); } fromPage = toPage; } }

} ]]>

VB.NET code sample Dim bookmarks As BookmarkCollection = document.Bookmarks Dim index As Integer = 0, fromPage As Integer = 0 While index < bookmarks.Count ' determine last page of next part Dim toPage As Integer = -1 If index = bookmarks.Count - 1 Then ' last bookmark - so just append all remaining pages toPage = document.Pages.Count Else ' not the last bookmark - append up to the page where ' the next bookmark points to Dim action As GoToAction = TryCast(bookmarks(index + 1).Actions(0), GoToAction) If action IsNot Nothing Then Dim destination As InternalDestination = TryCast(action.Destination, InternalDestination) If destination IsNot Nothing Then toPage = destination.Page.Index End If End If End If ' create a new part If -1 <> toPage Then Dim part As New Document() For pageIndex As Integer = fromPage To toPage - 1 part.Pages.Add(document.Pages(pageIndex).Clone()) Next Dim title As String = bookmarks(index).Title Using fileOut As New FileStream(String.Format("..\..\{0}.pdf", title), FileMode.Create, FileAccess.Write) Console.WriteLine("Writing {0} - {1} of {2}", title, index, bookmarks.Count) part.Write(fileOut) End Using fromPage = toPage End If index += 1 End While

End Using ]]>