To Merge Pdfs In Java

Merging PDFs in Java can be done using various libraries, but one of the most popular and versatile ones is iText. iText is a powerful library that allows you to create, manipulate, and extract content from PDF documents.

Merging Pdf’s in Java

The process of merging PDFs involves combining the content of multiple PDF documents into a single document.

This typically involves:

1.Reading the Input PDFs: Each PDF file is read and its content is loaded into memory.
2.Creating a New PDF Document: A new, empty PDF document is created to hold the combined content.
3.Copying Pages: The pages from the input PDFs are copied into the new PDF document in sequence.
4.Saving the Merged PDF: The new PDF document is saved to disk or another output stream.

Code Implementation:

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;
import java.io.FileOutputStream;

public class PDFMerger {
    public static void main(String[] args) {
        String[] files = { "input1.pdf", "input2.pdf", "input3.pdf" }; 
        String output = "merged.pdf";
        
        try {
            Document document = new Document();
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(output));
            document.open();
            
            for (String file : files) {
                PdfReader reader = new PdfReader(file);
                int n = reader.getNumberOfPages();
                for (int i = 1; i <= n; i++) {
                    copy.addPage(copy.getImportedPage(reader, i));
                }
                copy.freeReader(reader);
                reader.close();
            }
            
            document.close();
            System.out.println("PDF files merged successfully!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Explanation:

Import Statements: The necessary iText classes are imported.

File Paths: Input PDF file paths are stored in an array, and the output PDF file path is specified.

Creating Document and PdfCopy Instances: A new Document object and PdfCopy instance are created. PdfCopy is used to copy content from existing PDFs to the new PDF.
Opening the Document: The new PDF document is opened.
Reading and Copying Pages: For each input PDF file, a PdfReader object is created. Each page of the input PDF is imported and added to the new document using ‘pdfcopy’

closing Resources :The ‘pdfReader’ for each input file is closed after its pages are copied. Finally, the new PDF document is closed .

output:
PDF files merged successfully!

Leave a Comment

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

Scroll to Top