Tuesday, June 18, 2013

Merge pdf files

The MergePdf program can be used to merge or combine many pdf files together. The merged pdf file that will be generated is called mergedfile.pdf.

Note: Again you need to download iText library and add it to your classpath. It is used to generate
pdf file.

merge pdf files in Java


MergePdf source code:
import java.io.FileOutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;


public class MergePdf {
public static void main(String[] args){
try{
mergePdf(args);
}catch(ArrayIndexOutOfBoundsException aiobe){System.out.println("Invalid parameters input");}
}
public static void mergePdf(String[] srcs){
try{
//create document object
Document document = new Document();
//create pdf copy object to copy current document to the output mergedfile file
PdfCopy copy = new PdfCopy(document, new FileOutputStream("mergedfile.pdf"));
//open the document
document.open();
PdfReader pr;
int n;
for (int i = 0; i < srcs.length; i++) {
pr = new PdfReader(srcs[i]); //create reader object to read each input pdf file
n = pr.getNumberOfPages();//get the number of pages per pdf file
for (int page = 1; page <=n;page++) {
copy.addPage(copy.getImportedPage(pr, page)); //extract each page from the file
}
}
document.close(); //close the document
}catch(Exception e){e.printStackTrace();}
}
}

In the program code above, the PdfReader class is used to read an array of the pdf source files. You need to use the PdfCopy class to import all pages found on the PdfReader. When constructing the PdfCopy object you need to specify the Document object and the FileOuputStream object. The Document object will store all pdf pages while the FileOuputStream object specify the output file and write all pages to the file. This class has a method called getImportedPage. This method returns the pdf Page object based on the specified page number.

No comments:

Post a Comment