Merging pdf files in Java

Words
96
Reading
1 min
Listen
Play
9y

import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

public class MergePdf {
public static void main(String[] args) throws IOException {

  //Loading an existing PDF document
  File file1 = new File("d:/data/1.pdf");
  PDDocument doc1 = PDDocument.load(file1);
   
  File file2 = new File("d:/data/2.pdf");
  PDDocument doc2 = PDDocument.load(file2);
     
  File file3 = new File("d:/data/3.pdf");
  PDDocument doc3 = PDDocument.load(file3);
  //Instantiating PDFMergerUtility class
  PDFMergerUtility PDFmerger = new PDFMergerUtility();

  //Setting the destination file
  PDFmerger.setDestinationFileName("d:/data/result2.pdf");

  //adding the source files
  PDFmerger.addSource(file1);
  PDFmerger.addSource(file2);
  PDFmerger.addSource(file3);
  

  //Merging the documents
  PDFmerger.mergeDocuments();


  //Closing the documents
  doc1.close();
  doc2.close();
  doc3.close();

}
}



Posted on Utopian.io - Rewarding Open Source Contributors

Merging pdf files in Java | Ecency