In this post we’ll see a Java program to merge PDFs using OpenPDF library.
OpenPDF is open source software with a LGPL and MPL license. To know more about OpenPDF library and PDF examples check this post- Generating PDF in Java Using OpenPDF Tutorial
Merging PDFs using OpenPDF
- To merge documents you need to use PDFCopy class which makes copies of PDF documents.
- Using PDFReader open the source PDFs and get pages from the PDF using getImportedPage() method of the PDFCopy class.
Following Java program shows how two PDF documents can be merged using OpenPDF.
import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.List; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.pdf.PdfCopy; import com.lowagie.text.pdf.PdfImportedPage; import com.lowagie.text.pdf.PdfReader; public class PDFMerge { public static final String MERGED_PDF = "F://knpcode//result//OpenPDF//Merged.pdf"; public static void main(String[] args) { try { // Source PDFs as a list List<String> fileList = Arrays.asList("F://knpcode//PDF1.pdf", "F://knpcode//PDF2.pdf"); Document doc = new Document(); // Output stream to target PDF document PdfCopy copy = new PdfCopy(doc, new FileOutputStream(MERGED_PDF)); doc.open(); // Iterate through PDF files. for(String filePath : fileList) { PdfReader pdfreader = new PdfReader(filePath); int n = pdfreader.getNumberOfPages(); PdfImportedPage page; // go through pages of PDF to copy // all the pages to the target PDF for (int i = 1; i <= n; i++) { // grab page from input document page = copy.getImportedPage(pdfreader, i); // add content to target PDF copy.addPage(page); } copy.freeReader(pdfreader); } doc.close(); copy.close(); } catch (DocumentException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Related Posts
- Merging PDFs in Java Using iText
- Merging PDFs in Java Using PDFBox
- Generating PDF in Java Using OpenPDF Tutorial
- Generating PDF in Java Using iText Tutorial
- Generating PDF in Java Using PDFBox Tutorial
- How to Append to a File in Java
- Java Program to Find Maximum And Minimum Values in an Array
- Java Program to Convert Between Time Zones
That’s all for the topic Merging PDFs in Java Using OpenPDF. If something is missing or you have something to share about the topic please write a comment.
You may also like
for (int i = 1; i < n; i++) should be i<=1
I guess you meant i<=n, thanks for pointing out that omission.