
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to merge two PDFs using Java
Problem Description
How to merge two PDFs using Java.
Solution
Following is an example program to merge two pdf documents using Java.
import org.apache.pdfbox.multipdf.PDFMergerUtility; import org.apache.pdfbox.pdmodel.PDDocument; import java.io.File; import java.io.IOException; public class MergingPdfs { public static void main(String[] args) throws IOException { //Loading an existing PDF document File file1 = new File("C:/pdfBox/sample1.pdf"); PDDocument doc1 = PDDocument.load(file1); File file2 = new File("C:/pdfBox/sample2.pdf"); PDDocument doc2 = PDDocument.load(file2); //Instantiating PDFMergerUtility class PDFMergerUtility PDFmerger = new PDFMergerUtility(); //Setting the destination file PDFmerger.setDestinationFileName("C:/pdfBox/merged.pdf"); //adding the source files PDFmerger.addSource(file1); PDFmerger.addSource(file2); //Merging the two documents PDFmerger.mergeDocuments(); System.out.println("Documents merged"); //Closing the documents doc1.close(); doc2.close(); } }
java_apache_pdf_box
Advertisements