Pages Navigation Menu

Coding is much easier than you think

Splitting PDF File Using Java iText API

split pdf
 
Previously I wrote a tutorial about how to merge two or more PDF files. This tutorial we will learn about splitting a PDF with multiple pages into multiple PDFs using the Java iText API.
 

Library Required

 
itext-2.1.4.jar
 
File: SplitPDF.java
 

package com.simplecode.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;

public class SplitPDF {
	// Split PDF files in Java using iText JAR

	public static void main(String[] args) {
	 try {
	 	SplitPDF.splitPDF(new FileInputStream("C:\File.pdf"),
			new FileOutputStream("C:\Output1.pdf"), 1, 15);

		SplitPDF.splitPDF(new FileInputStream("C:\File.pdf"),
			new FileOutputStream("C:\Output2.pdf"), 15, 30);

	     } catch (Exception e) {
		System.err.println(e.getMessage());
	     }
	}

	public static void splitPDF(FileInputStream inputStream,
			FileOutputStream outputStream, int fromPage, int toPage) {

		Document document = new Document();

		try {
			PdfReader inputPDF = new PdfReader(inputStream);
			int totalPages = inputPDF.getNumberOfPages();

			// Make fromPage equals to toPage if it is greater
			if (fromPage > toPage) {
				fromPage = toPage;
			}
			if (toPage > totalPages) {
				toPage = totalPages;
			}

			// Create a writer for the outputstream
			PdfWriter writer = PdfWriter.getInstance(document, outputStream);
			document.open();
			// Holds the PDF data
			PdfContentByte cb = writer.getDirectContent();
			PdfImportedPage page;

			while (fromPage <= toPage) {
				document.newPage();
				page = writer.getImportedPage(inputPDF, fromPage);
				cb.addTemplate(page, 0, 0);
				fromPage++;
			}
			outputStream.flush();
			document.close();
			outputStream.close();
		} catch (Exception e) {
			System.err.println(e.getMessage());
		} finally {
			if (document.isOpen())
				document.close();
			try {
				if (outputStream != null)
					outputStream.close();
			} catch (IOException ioe) {
				System.err.println(ioe.getMessage());
			}
		}
	}
}

 

About Mohaideen Jamil


Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.