Removing Pages from a PDF Document using Java
Program to remove pages from an existing document a PDF document. The external jar file is required to import in the program. Below is the implementation for the same.
Remove a page from an existing PDF document using the removePage() method of the PDDocument class.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
- Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below.
File file = new File(“path of the document”)
- List the number of pages that exists in the PDF document using the getNumberOfPages() method as shown below.
int noOfPages= document.getNumberOfPages();
- Remove a page from the PDF document using the removePage() method of the PDDocument class. To this method, pass the index of the page that is to be deleted. While specifying the index for the pages in a PDF document, keep in mind that indexing of these pages starts from zero.
- After removing the page, save the PDF document using the save() method of the PDDocument class as shown in the following code block.
- Finally, close the document using the close() method of the PDDocument class as shown below.
Note: External Jar required (Download by clicking here).
Below is the implementation of the above approach: