Showing posts with label split pdf. Show all posts
Showing posts with label split pdf. Show all posts

Sunday, June 16, 2013

Split Pdf

The SplitPdf program can be used to split a pdf file to many pdf files. You can split the pdf file in every any page that you want. For example, if you have 100-page pdf file and you split it in every two pages, you will get fifty pdf files. Each file has two pages.
The API used to split a pdf file is iText. It is a useful and  free library. For more information about iText, you can visit its web site listed at the right side bar of this post.

split pdf in Java

SplitPdf source code:

import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;

public class SplitPdf {
public static void main(String[] args){
try{

splitPdf(args[0],Integer.parseInt(args[1]));

}catch(ArrayIndexOutOfBoundsException aiobe){System.out.println("Invalid parameters input");}

}

public static void splitPdf(String src, int every_n_page){
try{
Document doc=null; //declare document
PdfReader pr=new PdfReader(src); //create pdf reader object
PdfCopy pc=null; //declare pdf copy object
int start=0; //initialize the start variable

for(int i=1;i<=pr.getNumberOfPages();i++){ //loop through the pdf document
//split the pdf document in every n page
if(i%every_n_page==0){
doc=new Document();
pc=new PdfCopy(doc, new FileOutputStream("split"+i+".pdf"));
doc.open();
for(int page=start+1;page<=i;page++)
pc.addPage(pc.getImportedPage(pr, page));
start+=every_n_page;
doc.close();
}
}
}catch(Exception e ) {}
}



}

To split a Pdf file to many Pdf files. Firstly, you need to have a PdfReader object to get all pages in the source Pdf file. Once you have the PdfReader object, you can use the PdfCopy class to get every Pdf page to be added to the Document object and write the Document out to the output file.
Merge or Combine PDF, Txt, Images