In this tutorial we show you how to extract and save single pages of a multiple paged PDF file into separate PDF files.
- Import the trial Developer License:
License.Import(new StreamReader(@"C:\Users\Joe\license.xml"));
- Allow multi selection of only PDF files using OpenFileDialog:
// Create a Open File Dialog that allows you to select multiple files
OpenFileDialog OpFile = new OpenFileDialog();
OpFile.Multiselect = true;
//show only PDF Files
OpFile.Filter = "PDF Files (*.pdf)|*.pdf";
//Do nothing if someone clicks on cancel
if (OpFile.ShowDialog() != System.Windows.Forms.DialogResult.OK)
{
...
- Use PagesModel to split the file:
//Create a new PagesModel object and open the selected file.
PagesModel model = new PagesModel();
model.OpenPDF(OpFile.FileName);
- Create a loop with a defined int called pageIndex set to zero to count the pages:
//Define a string called partsFolder to get the directory information for the selected file
String partsFolder = Path.GetDirectoryName(OpFile.FileName);
partsFolder = Path.Combine(partsFolder, Path.GetFileNameWithoutExtension(OpFile.FileName));
Directory.CreateDirectory(partsFolder);
if (model.Count > 1) //If the PDF has more than one page then count the pages
{
for (int pagelndex = 0;
pagelndex < model.Count;
pagelndex++ // same as saying “pagelndex = pagelndex + 1”
)
}
...
}
- Clear model of any selection and add the new pageIndex:
model.Selection.Clear();
model.Selection.Add(pagelndex);
...
- Manage if there is only one page in the selected file:
//Name the extracted pages to the source file name plus the page number it relates to using pageIndex
String path = Path.Combine(partsFolder, Path.GetFileName(OpFile.FileName));
path = Path.ChangeExtension(path, "." + (pageIndex + 1).ToString() + ".pdf");
...
- Save and extract the pages:
model.Save(path, true);
...
- Just save a copy if the selected file only has one page:
else // If there is only one page in the selected PDF File
{
String path = Path.Combine(partsFolder, Path.GetFileName(OpFile.FileName));
path = Path.ChangeExtension(path, ".1.pdf");
File.Copy(OpFile.FileName, path, true);
File.SetAttributes(path, FileAttributes.Normal); // make sure the copy is not readonly
}
- Close Model:
model.Close();
...