- Back to Home »
- Merging PDF files in Java
Posted by : Unknown
Saturday, November 5, 2011
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
Hello,
ReplyDeleteThe file input streams added to the sources list are not closed!! Might cause memory leaks?
Thanks
soulless being, You are right they would cause memory leak, but the idea is just to highlight the merging capability of the library and nothing else.
ReplyDeleteThanks! It works!
ReplyDelete