Monday, May 16, 2011

Split existing pdf file into two pdf files

Required Jar : itext-2.1.2.jar
Source Code:

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfReader;
public class SplitPdf {
public static void main( String[] args ) {
try {
String fileName = "D:\\Ganga\\ganga_Test.pdf";
String delFileName = "D:\\Ganga\\ganga_Test_Del.pdf";
String newFileName = "D:\\Ganga\\ganga_Test_New.pdf";
PdfReader reader = new PdfReader( fileName );
// List of pages deleted from the existing file
List newPages = new ArrayList();
newPages.add( 4 );
// newPages.add( 5 );
com.lowagie.text.Document document =
new com.lowagie.text.Document( reader
.getPageSizeWithRotation( 1 ) );
PdfCopy copy =
new PdfCopy( document, new FileOutputStream( delFileName ) );
PdfCopy newCopy =
new PdfCopy( document, new FileOutputStream( newFileName ) );
document.open();
for ( int pageNumber = 1; pageNumber <= reader.getNumberOfPages(); pageNumber++ ) {
if ( !newPages.contains( pageNumber ) ) {
copy.addPage( copy.getImportedPage( reader, pageNumber ) );
} else {
newCopy
.addPage( copy.getImportedPage( reader, pageNumber ) );
}
}
document.close();
} catch ( FileNotFoundException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch ( DocumentException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch ( IOException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

No comments:

Post a Comment