Delete PDF Pages in Java

Use the document page collection when you need to remove one or more pages from a PDF.

Delete a single page

Use this example when you need to remove one page by its index.

  1. Open the source PDF Document.
  2. Delete the target page from the page collection.
  3. Save the updated document.
public static void deletePage(Path inputFile, Path outputFile) {
    try (Document document = new Document(inputFile.toString())) {
        document.getPages().delete(2);
        document.save(outputFile.toString());
    }
}

Delete multiple pages

Use this example when several pages should be removed in one operation.

  1. Open the source PDF Document.
  2. Pass the page indexes to delete from the page collection.
  3. Save the modified PDF.
public static void deleteBunchPages(Path inputFile, Path outputFile) {
    try (Document document = new Document(inputFile.toString())) {
        document.getPages().delete(new Integer[]{2, 3, 4});
        document.save(outputFile.toString());
    }
}