Extract PDF Pages in Java

Aspose.PDF for Java lets you copy selected pages into a new destination document.

Extract a single page

Use this example when you need to save one page from the source PDF into a separate document.

  1. Open the source PDF Document and create a destination document.
  2. Copy the target page into the destination page collection.
  3. Save the new PDF.
public static void extractPage(Path inputFile, Path outputFile) {
    try (Document srcDocument = new Document(inputFile.toString());
         Document dstDocument = new Document()) {
        dstDocument.getPages().add(srcDocument.getPages().get_Item(2));
        dstDocument.save(outputFile.toString());
    }
}

Extract multiple pages

Use this example when you need to copy several pages into a separate PDF.

  1. Open the source PDF Document and create a destination document.
  2. Iterate through the selected page indexes and add them to the destination.
  3. Save the extracted-pages document.
public static void extractBunchPages(Path inputFile, Path outputFile) {
    try (Document document = new Document(inputFile.toString());
         Document anotherDocument = new Document()) {
        Integer[] pages = {2, 3};
        for (Integer pageIndex : pages) {
            anotherDocument.getPages().add(document.getPages().get_Item(pageIndex));
        }
        anotherDocument.save(outputFile.toString());
    }
}