Archive for November 2011
Merging PDF files in Java
package com.gognamunish.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.pdfbox.util.PDFMergerUtility;
/**
* Merges pdf files into one final pdf.
*
* @author Munish Gogna
*/
public class PDFMerge {
public static void main(String[] args) throws Exception {
// Get the byte streams from any source (maintain order)
List<InputStream> sourcePDFs = new ArrayList<InputStream>();
sourcePDFs.add(new FileInputStream(new File("pdf1.pdf")));
sourcePDFs.add(new FileInputStream(new File("pdf2.pdf")));
sourcePDFs.add(new FileInputStream(new File("pdf3.pdf")));
// initialize the Merger utility and add pdfs to be merged
PDFMergerUtility mergerUtility = new PDFMergerUtility();
mergerUtility.addSources(sourcePDFs);
// set the destination pdf name and merge input pdfs
mergerUtility.setDestinationFileName("merged.pdf");
mergerUtility.mergeDocuments();
}
}
The library is rich and provides many options out of the box that can be useful when it comes to playing with PDFs, worth a try !!!http://pdfbox.apache.org/index.html
cheers, Munish Gogna
