Split PDF into Multiple PDFs using a Range of Pages in C#, VB.NET

Splitting a multi-page PDF into single pages is perfectly supported by Spire.PDF. However, it's more common that you may want to extract selected range of pages and save as a new PDF document. In this post, you'll learn how to split a PDF file based on a range of pages via Spire.PDF in C#, VB.NET.

Here come the detailed steps:

Step 1: Initialize a new instance of PdfDocument class and load the test file.

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Sample.pdf");

Step 2: Create a new PDF document named as pdf1, initialize a new instance of PdfPageBase class.

PdfDocument pdf1 = new PdfDocument();
PdfPageBase page;

Step 3: Add new page to pdf1 based on the original page size and the specified margins, draw the original page element to the new page using Draw() method. Use for loop to select pages that you want them to be divided.

for (int i = 0; i < 5; i++)
{
    page = pdf1.Pages.Add(pdf.Pages[i].Size, new Spire.Pdf.Graphics.PdfMargins(0));
    pdf.Pages[i].CreateTemplate().Draw(page, new System.Drawing.PointF(0, 0));
}

Step 4: Save the file.

pdf1.SaveToFile("DOC_1.pdf");

Step 5: Repeat step 2 to step 4 to extract another range of pages to a new PDF file. Change the parameter i to choose the pages.

PdfDocument pdf2 = new PdfDocument();
for (int i = 5; i < 8; i++)
{
    page = pdf2.Pages.Add(pdf.Pages[i].Size, new Spire.Pdf.Graphics.PdfMargins(0));
    pdf.Pages[i].CreateTemplate().Draw(page, new System.Drawing.PointF(0, 0));
}
pdf2.SaveToFile("DOC_2.pdf");

Result:

Split PDF into Multiple PDFs using a Range of Pages in C#, VB.NET

Split PDF into Multiple PDFs using a Range of Pages in C#, VB.NET

Full code:

[C#]
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Sample.pdf");

PdfDocument pdf1 = new PdfDocument();
PdfPageBase page;
for (int i = 0; i < 5; i++)
{
    page = pdf1.Pages.Add(pdf.Pages[i].Size, new Spire.Pdf.Graphics.PdfMargins(0));
    pdf.Pages[i].CreateTemplate().Draw(page, new System.Drawing.PointF(0, 0));
}
pdf1.SaveToFile("DOC_1.pdf");

PdfDocument pdf2 = new PdfDocument();
for (int i = 5; i < 8; i++)
{
    page = pdf2.Pages.Add(pdf.Pages[i].Size, new Spire.Pdf.Graphics.PdfMargins(0));
    pdf.Pages[i].CreateTemplate().Draw(page, new System.Drawing.PointF(0, 0));
}
pdf2.SaveToFile("DOC_2.pdf");
[VB.NET]
Dim pdf As New PdfDocument()
pdf.LoadFromFile("Sample.pdf")

Dim pdf1 As New PdfDocument()
Dim page As PdfPageBase
For i As Integer = 0 To 4
	page = pdf1.Pages.Add(pdf.Pages(i).Size, New Spire.Pdf.Graphics.PdfMargins(0))
	pdf.Pages(i).CreateTemplate().Draw(page, New System.Drawing.PointF(0, 0))
Next
pdf1.SaveToFile("DOC_1.pdf")

Dim pdf2 As New PdfDocument()
For i As Integer = 5 To 7
	page = pdf2.Pages.Add(pdf.Pages(i).Size, New Spire.Pdf.Graphics.PdfMargins(0))
	pdf.Pages(i).CreateTemplate().Draw(page, New System.Drawing.PointF(0, 0))
Next
pdf2.SaveToFile("DOC_2.pdf")