Hello friends, previously I told you How to merge more than one PDF files using Java, now I am going to tell you How to split a PDF file using Java. Using this java code you can split one PDF file to two or more PDF file.
Split2PDF.java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.techzoop.splitpdf;
/**
*
* @author ARPAN
*/
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 Split2PDF {
public static void main(String[] args) {
try {
Split2PDF.splitPDF(new FileInputStream("C:\\Users\\USER\\Desktop\\11\\New_Merged.pdf"),
new FileOutputStream("C:\\Users\\USER\\Desktop\\11\\Split1.pdf"), 1, 1);
Split2PDF.splitPDF(new FileInputStream("C:\\Users\\USER\\Desktop\\11\\New_Merged.pdf"),
new FileOutputStream("C:\\Users\\USER\\Desktop\\11\\Split2.pdf"), 2, 2);
} 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());
}
}
}
}
If you will find any error, feel free to ask.
Library required:
For running this code properly the following library file is required. Click the bellow library file name to download the library.
itext-2.1.4.jar
0 comments:
Post a Comment