Extract PDF Pages in Java
Contents
[
Hide
]
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.
- Open the source PDF Document and create a destination document.
- Copy the target page into the destination page collection.
- 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.
- Open the source PDF Document and create a destination document.
- Iterate through the selected page indexes and add them to the destination.
- 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());
}
}