This basic tutorial elaborates the details on how to split PDF by pages in Java. You can choose to split each page of the input document or some specific pages based on the page numbers in the source file. This article includes the steps and code sample which summarizes how using Java split PDF pages functionality can be achieved.
Steps to Split PDF by Pages in Java
- Configure the project by adding the reference to Aspose.PDF for Java from the Maven repository to split PDF pages
- Load the source PDF document using the Document class instance for creating multiple PDF files
- Initialize a blank PDF document and add each page of input files one by one using the Page class
- Split the PDF file by creating a separate PDF file corresponding to each page of the input file
If you want to split PDF Java based application can be created with the help of these steps easily. First of all, the source PDF document is loaded and each of its pages is copied to a blank document. Subsequently, the newly created PDF is saved one after another as per the requirements.
Code to Split PDF by Pages in Java
import com.aspose.pdf.Document; | |
import com.aspose.pdf.License; | |
public class SplitPDFByPagesInJava { | |
public static void main(String[] args) throws Exception { // main method to split PDF to multiple documents | |
// Instantiate the license to avoid trial version limitations | |
// while splitting the PDF files | |
License asposePdfSplitLicense = new License(); | |
asposePdfSplitLicense.setLicense("Aspose.pdf.lic"); | |
// Load input PDF file | |
Document documentToSplit = new Document("input.pdf"); | |
// Loop through each page | |
for (com.aspose.pdf.Page page : documentToSplit.getPages()) | |
{ | |
// Create a new Document class object to split PDF pages | |
Document splitPDF = new Document(); | |
// Add each page to the document | |
splitPDF.getPages().add(page); | |
// Save the splitted pages | |
splitPDF.save("Page number " + page.getNumber() + ".pdf"); | |
} | |
System.out.println("Done"); | |
} | |
} |
This sample code is a basic example of how using Java split PDF into multiple files feature can be integrated into your applications. This code provides access to each page in the source document hence enabling the use of Page class features before saving it as a separate PDF like adding some image, stamping the page, deleting unused resources, making it grey scale, setting some background, setting some headers/footers and so on. Similarly, after adding a page to a new PDF document, you can add document title, set page layout, show/hide toolbar and menu bar, and set document windows position to name a few.
To split PDF Java based application is demonstrated here with the help of a running code. However, if you want to learn the details about merging PDF files, refer to the article on how to merge PDF files in Java.