Merger > Programming > Merging Documents

Merging Two Documents

The following code will merge two PDF documents together.

[Java]
    MergeDocument document = MergeDocument.merge("[PhysicalPath]/DocumentA.pdf",
                                                 "[PhysicalPath]/DocumentB.pdf");
    document.draw("[PhysicalPath]/MyDocument.pdf");

Appending Documents

The following code will load a PDF document, append a range of pages from one document to it, and then append another entire document to it.

[Java]
    MergeDocument document = new MergeDocument("[PhysicalPath]/DocumentA.pdf");
    document.append("[PhysicalPath]/DocumentB.pdf", 1, 2);
    document.append("[PhysicalPath]/DocumentC.pdf");
    document.draw("[PhysicalPath]/MyDocument.pdf");

Importing From Streams

The following code shows how to perform the previous example using FileInputstream objects instead of files.

[Java]
    MergeDocument document = new MergeDocument(new PdfDocument(streamA));
    document.append(new PdfDocument(streamB), 1, 2);
    document.append(new PdfDocument(streamC));
    document.draw("[PhysicalPath]/MyDocument.pdf");

Importing From Byte Array

The following code shows how to import a PDF document using byte array. Similarly we can aslo use ByteArrayInputStream.

[Java]
    FileInputStream file = new FileInputStream("[PhysicalPath]/MyDocument.pdf");
    byte[] data = new byte[file.available()];
    file.read(data);
    MergeDocument document = new MergeDocument(new PdfDocument(data));
    document.append(new PdfDocument(streamB), 1, 2);
    document.append(new PdfDocument(streamC));
    document.draw("[PhysicalPath]/MyDocument.pdf");

NOTE: The examples in this topic show how to merge PDF documents that are not going to be reused multiple times. For details on how to most efficiently handle PDF documents that will be used multiple times, see the Performance Considerations topic.

See Also

MergeDocument Class | PdfDocument Class | Programming With Merger for Java | Performance Considerations