Split PDF Files in Java

Spire.PDF for Java allows splitting a pdf file by the following ways:

  • Split every page of the PDF into a separate file
  • Split the PDF into multiple files by a range of pages

Below code examples demonstrate how to use Spire.PDF for Java to split a PDF file.

The original PDF file:

Split PDF Files in Java

Split every page of the PDF into a separate file

import com.spire.pdf.*;

public class SplitPDF {
    public static void main(String[] args)
    {

        //Load the PDF file
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("sample.pdf");

        //Split every page of the PDF into a separate file
        doc.split("output/splitDocument-{0}.pdf", 0);
        doc.close();
    }
}

Split PDF Files in Java

Split the PDF into multiple files by a range of pages

import com.spire.pdf.*;
import com.spire.pdf.graphics.PdfMargins;

import java.awt.geom.Point2D;

public class SplitPDF {
    public static void main(String[] args)
    {

        //Load the PDF file
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("sample.pdf");

        //Create a new PDF file
        PdfDocument newDoc1 = new PdfDocument();

        PdfPageBase page;

        //Add 2 pages to the new PDF, and draw the content of page 1-2 of the original PDF to the new added pages 
        for(int i = 0;i<2;i++)
        {
            page = newDoc1.getPages().add(doc.getPages().get(i).getSize(), new PdfMargins(0));
            doc.getPages().get(i).createTemplate().draw(page, new Point2D.Float(0,0));
        }

        //Save the result file
        newDoc1.saveToFile("split/Doc1.pdf");

        //Create a new PDF file
        PdfDocument newDoc2 = new PdfDocument();

        //Add 3 pages to the new PDF, and draw the content of page 3-5 of the original PDF to the new added pages
        for(int i = 2;i<5;i++)
        {
            page = newDoc2.getPages().add(doc.getPages().get(i).getSize(), new PdfMargins(0));
            doc.getPages().get(i).createTemplate().draw(page, new Point2D.Float(0,0));
        }

        //Save the result file
        newDoc2.saveToFile("split/Doc2.pdf");
    }
}

Split PDF Files in Java