Split a PDF file

<< Click to Display Table of Contents >>

Navigation:  Gnostice Document Studio .NET > Going Deeper > Document Engines > Working with PDF > Enhancement >

Split a PDF file

In this section we present example code to split a PDF files into multiple ones. We attain the splitting by just creating a new file and adding pages from the original one. Before proceeding further please make sure that the prerequisite steps as listed in the Document Engines parent topic are followed.

 

Given below is the sample code that creates a new PDF document by taking a subset of pages from the original PDF.

 

using (var pdfDoc = new PDF())
using (var newPdfDoc = new PDF())
{
   string inputPdfFile = @"input.pdf";
   int startPageNum = 3;
   int endPageNum = 5;
   pdfDoc.LoadDocument(inputPdfFile);
   for (int pageNum = startPageNum; pageNum <= endPageNum; ++pageNum)
   {
      var page = pdfDoc.GetPage(pageNum);
      newPdfDoc.AddPage(page);
   }
   var newFileName = $"{System.IO.Path.GetFileNameWithoutExtension(inputPdfFile)}_{startPageNum}_{endPageNum}.pdf";
   newPdfDoc.Save(newFileName);
}