How to remove pages from a PDF document using Java



Problem Description

How to remove pages from a PDF document using Java.

Solution

Following is an example program to remove pages from a PDF document using Java.

import java.io.File; 
import java.io.IOException; 
import org.apache.pdfbox.pdmodel.PDDocument;  

public class RemovingPagesFromPdf { 
   public static void main(String args[]) throws IOException {  
      
      //Loading an existing document 
      File file = new File("C:/pdfBox/RemovePages_IP.pdf"); 
      PDDocument doc = PDDocument.load(file); 
       
      //Listing the number of existing pages       
      System.out.print(doc.getNumberOfPages()); 
       
      for(int i = 0; i<5; i++){
         
         //removing the pages 
         doc.removePage(i); 
      } 
      System.out.println("page removed");       
      
      //Saving the document 
      doc.save("C:/pdfBox/RemovePages_OP.pdf");     
      
      //Closing the document  
      doc.close(); 
   }  
} 

Input

Remove Input

Output

Remove Output
java_apache_pdf_box
Advertisements