/*
MyPDFConcat.java
you need to have the iText jar file in your classpath

(c)Jobin Wilson
*/

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;

//utility to combine pdf files in java
public class MyPDFConcat {

public static void main(String args[]) {
if (args.length < 2) {
System.out.println("args: inputfile1 inputfile2...outputfile");
}
else {
try {
ArrayList fileList = new ArrayList();
int offset = 0;
int i = 0;
String outputFileName = args[args.length-1];
Document document = null;
PdfCopy writer = null;
for(i=0;i<args.length-1;i++)
{
PdfReader reader = new PdfReader(args[i]);
reader.consolidateNamedDestinations();
int n = reader.getNumberOfPages();
offset = offset + n;

if (i == 0) {
document = new Document(reader.getPageSizeWithRotation(1));
//create document if it is first time in one pdf
writer = new PdfCopy(document, new FileOutputStream(outputFileName));
document.open();
}
PdfImportedPage page; //add content to the output
for (int j = 1; j <= n; j++) {
page = writer.getImportedPage(reader, j);
writer.addPage(page);
System.out.println("Done with the page" + j);
}
writer.freeReader(reader);

}

document.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}