Merge two PDF files

12 / Jul / 2010 by Uday Pratap Singh 1 comments

In my current project the user has the option to add pdf file into the system. Recently we got the requirement to add a cover page to each pdf document that user downloads. We were already using the iText API for generating pdf so the task to do that was easy. After going through the documentation of iText I found a way to merge two pdf files.

 
try{
            PdfReader pdfReader1 = new PdfReader("firstFile.pdf");
            PdfReader pdfReader2 = new PdfReader("secondFile.pdf");
            PdfCopyFields finalCopy = new PdfCopyFields(new FileOutputStream("finalCopy.pdf"));
            finalCopy.open();
            [pdfReader1,pdfReader2].each {PdfReader pdfReader ->
                   finalCopy.addDocument(pdfReader);
            }
            finalCopy.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

Hope it helps
Uday Pratap Singh
uday@intelligrape.com

FOUND THIS USEFUL? SHARE IT

comments (1 “Merge two PDF files”)

Leave a Reply

Your email address will not be published. Required fields are marked *