Splitting a PDF document is the process of saving each page into a new, separate PDF document. For example, splitting a three-page PDF document will produce three, single-page PDF documents.
To split a PDF document using ImageGear:
-
Read the PDF document into a
System.IO.Stream
object. -
Read the stream using
ImGearFileFormats.LoadDocument()
, casting theImGearDocument
object returned to anImGearPDFDocument
object. -
Determine the PDF page count using the
ImGearPDFDocument.Pages
property. -
For each PDF page:
- Construct a new
ImGearPDFDocument
object to create an empty PDF document. - Add the page to the empty PDF document using the
ImGearPDFDocument.InsertPages()
method. - Save the single-page PDF to disk or memory using the
ImGearPDFDocument.Save()
method.
- Construct a new
The following is a sample method that illustrates how to split a single PDF document into several single-page PDF documents:
PDF support needs to be initialized first for this snippet to work. To get familiar with initializing IGNET, initializing PDF support, loading a PDF, saving a PDF, and terminating PDF support, try any one of the tutorials.
C#
using System;
using System.IO;
using System.Text;
using ImageGear.Core;
using ImageGear.Formats;
using ImageGear.Windows.Forms;
using ImageGear.Formats.PDF;
public void SplitPDFDocument(String inputPath, String outputDirectory)
{
const int FIRST_PAGE = 0;
const int ONE_PAGE = 1;
// Ensure output directory exists.
if ( !System.IO.Directory.Exists(outputDirectory) )
{
Directory.CreateDirectory(outputDirectory);
}
// Open file for reading.
using ( FileStream pdfData = new FileStream(inputPath, FileMode.Open,
FileAccess.Read) )
{
// Read PDF document to memory.
using ( ImGearPDFDocument igSourceDocument = ImGearFileFormats.LoadDocument(
pdfData, FIRST_PAGE, (int)ImGearPDFPageRange.ALL_PAGES)
as ImGearPDFDocument )
{
// For each page in document.
for ( int i = 0; i < igSourceDocument.Pages.Count; i++ )
{
// Construct the output filepath.
String outputFileName = String.Format("{0}_{1}.pdf",
Path.GetFileNameWithoutExtension(inputPath), i + 1);
String outputPath = System.IO.Path.Combine(outputDirectory, outputFileName);
// Create a new empty PDF document.
using ( ImGearPDFDocument igTargetDocument = new ImGearPDFDocument() )
{
// Insert page into new PDF document.
igTargetDocument.InsertPages(
(int)ImGearPDFPageNumber.BEFORE_FIRST_PAGE, igSourceDocument,
i, ONE_PAGE, ImGearPDFInsertFlags.DEFAULT);
// Save new PDF document to file.
igTargetDocument.Save(outputPath, ImGearSavingFormats.PDF,
FIRST_PAGE, FIRST_PAGE, ONE_PAGE,
ImGearSavingModes.OVERWRITE);
}
}
}
}
}
Refer to Samples and Demos documentation.