Split PDF pages in C# and VB.NET

Manipulate PDF
11/2/2011

Downloads

The following code sample shows how to split PDF pages in C# and VB.NET

Splitting PDF pages is quite similar to append PDF pages. The only difference is that appending copy pages from PDF documents onto another existing PDF document, while splitting copy pages onto a new PDF document. The following sample code shows how to split a PDF document with multiple pages into several PDF documents each containing a single page.

How to split pdf in C# / VB.NET

C# code sample

1 using ( FileStream inFile = new FileStream( @"..\..\..\inputDocuments\PackingLightBrochure.pdf", FileMode.Open, FileAccess.Read ) ) 2 { 3 // open the source document 4 Document documentIn = new Document( inFile ); 5 6 // enumerate the pages in the source document 7 for ( int i=0; i<documentIn.Pages.Count; i++ ) 8 { 9 // create the target document 10 Document documentOut = new Document(); 11 12 // append page i to the target document, we don't want to change the documentIn, so Clone the page. 13 documentOut.Pages.Add( documentIn.Pages[i].Clone() ); 14 15 // write the target document to disk 16 using ( FileStream outFile = new FileStream( 17 string.Format( @"..\..\split_{0}.pdf", i ), 18 FileMode.Create, FileAccess.Write ) ) 19 { 20 documentOut.Write( outFile ); 21 } 22 } 23 }

VB.NET code sample

1 Using inFile As New FileStream("..\..\..\inputDocuments\PackingLightBrochure.pdf", FileMode.Open, FileAccess.Read) 2 ' open the source document 3 Dim documentIn As New Document(inFile) 4 For i As Integer = 0 To documentIn.Pages.Count - 1 5 6 ' enumerate the pages in the source document 7 ' create the target document 8 Dim documentOut As New Document() 9 10 ' append page i to the target document, we don't want to change the documentIn, so Clone the page. 11 documentOut.Pages.Add(documentIn.Pages(i).Clone()) 12 13 ' write the target document to disk 14 Using outFile As New FileStream(String.Format("..\..\split_{0}.pdf", i), FileMode.Create, FileAccess.Write) 15 documentOut.Write(outFile) 16 End Using 17 18 Next 19 End Using