Skip to content
Related Articles

Related Articles

Improve Article

Splitting a PDF into many using Java

  • Difficulty Level : Expert
  • Last Updated : 08 Dec, 2020
Geek Week

Program to split the PDF document into multiple PDFs. Below is the implementation for the same using JAVA. The prerequisite of this topic is that you have already installed apache library 

Approach:

  • Load the PDF from the computer.
    • Load the PDF using the class called PDDocument.
    • Use load() function of PDdocument class to load the file.
       
  • Run the Splitter Class to split PDF.
    • Splitter is a class used to split PDF.
    • Use Split() function of the splitter class to split the PDF.
       
  • Using Iterator to count pages.
    • Split the pages into many so that count the pages after the split() function, and use that to create a finite number of splits PDF.
    • Save all the PDFs.
    • Close the document.

Below is the implementation of the above approach:

Java




// Splitting a PDF in to many using Java
import org.apache.pdfbox.multipdf.Splitter;
import org.apache.pdfbox.pdmodel.PDDocument;
  
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Iterator;
  
public class SplitPdf {
    public static void main(String[] args)
        throws IOException
    {
  
        // Loading PDF
        File pdffile
            = new File("C:/Desktop/Java/sample.pdf");
        PDDocument document = PDDocument.load(pdffile);
  
        // Splitter Class
        Splitter splitting = new Splitter();
  
        // Splitting the pages into multiple PDFs
        List<PDDocument> Page = splitting.split(document);
  
        // Using a iterator to Traverse all pages
        Iterator<PDDocument> iteration
            = Page.listIterator();
  
        // Saving each page as an individual document
        int j = 1;
        while (iteration.hasNext()) {
            PDDocument pd = iteration.next();
            pd.save("C:/Desktop/Java/Generated/sample-"
                    + j++ + ".pdf");
        }
        System.out.println("Splitted Pdf Successfully.");
        document.close();
    }
}

Before the execution of the program:



 

After execution of the program:

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :