Wednesday, April 13, 2011

Split PDF files in Java using iText JAR

Consider the following code in java:

public static void splitPDF(InputStream inputStream,
        OutputStream 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();
        PdfContentByte cb = writer.getDirectContent(); // Holds the PDF data
        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) {
        e.printStackTrace();
    } finally {
        if (document.isOpen())
            document.close();
        try {
            if (outputStream != null)
                outputStream.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

In above code, we have created a method splitPDF () that can be used to extracts pages out of a PDF and write it into another PDF. The code is pretty much self explanatory and is similar to the one to merge PDF files.
Thus, if you need to split an input.pdf (having 20 pages) into output1.pdf (1-12 pages of input.pdf) and output2.pdf (13-20 of input.pdf), you can call the above method as follow:

public static void main(String[] args) {
    try {
        MergePDF.splitPDF(new FileInputStream("C:\\input.pdf"),
                    new FileOutputStream("C:\\output1.pdf"), 1, 12);
        MergePDF.splitPDF(new FileInputStream("C:\\input.pdf"),
                    new FileOutputStream("C:\\output2.pdf"), 13, 20);
 
    } catch (Exception e) {
        e.printStackTrace();
    }
}

No comments:

Post a Comment

Chitika