Extract pages from a PDF in C#

Extracting pages is the process of selecting pages from a source document and then saving the selected pages in a new document.

Extract pages from multipage files of the following formats:

Extracting pages from a PDF

The code below extracts pages from a multipage PDF file to a multipage output PDF file using the ClonePages method:

using GdPicturePDF gdpicturePDF = new GdPicturePDF();
using GdPicturePDF gdpictureDestPDF = new GdPicturePDF();
gdpicturePDF.LoadFromFile(@"C:\temp\source.pdf");
gdpictureDestPDF.NewPDF();
// Extract specified pages to the output file.
gdpictureDestPDF.ClonePages(gdpicturePDF, "2-3;5");
gdpictureDestPDF.SaveToFile(@"C:\temp\output.pdf");

To ensure your program executes correctly, check the status of the used methods with the GetStat method.

Extracting pages from a TIFF

The code below extracts pages from a multipage TIFF file to a multipage output TIFF file using the TiffExtractPage method. Each page is extracted separately:

using GdPictureImaging gdpictureImaging = new GdPictureImaging();
int sourceImageID;
int outputID = 0;
int imageID;
string source = @"C:\temp\source.tif", output = @"C:\temp\output.tif";
sourceImageID = gdpictureImaging.CreateGdPictureImageFromFile(source);
// Set the page numbers you want to extract.
int[] pages = { 1, 3, 5 };
bool firstPage = true;
foreach (int page in pages)
{
Stream pStream = new MemoryStream();
gdpictureImaging.TiffExtractPage(sourceImageID, page, pStream);
imageID = gdpictureImaging.CreateGdPictureImageFromStream(pStream);
if (firstPage)
{
// If it's the first image, create a new multipage TIFF file.
gdpictureImaging.TiffSaveAsMultiPageFile(outputID, output, TiffCompression.TiffCompressionAUTO);
outputID = imageID;
firstPage = false;
}
else
{
// If it's the second or later image, add to the previously created multipage TIFF file.
gdpictureImaging.TiffAddToMultiPageFile(outputID, imageID);
gdpictureImaging.ReleaseGdPictureImage(imageID);
};
}
gdpictureImaging.TiffCloseMultiPageFile(outputID);
gdpictureImaging.ReleaseGdPictureImage(outputID);
gdpictureImaging.ReleaseGdPictureImage(sourceImageID);

To ensure your program executes correctly, check the status of the used methods with the GetStat method.