ImageGear .NET v25.2 - Updated
Merge Multiple PDFs
Developer Guide > How to Work with... > PDF > How to... > Merge Multiple PDFs

The following example illustrates how to merge two multi-page PDF documents into one document:

PDF support needs to be initialized first for this snippet to work. To get familiar with initializing IGNET, initializing PDF support, loading a PDF, saving a PDF, and terminating PDF support, try any one of the tutorials.
C#
Copy Code
using ImageGear.Formats.PDF;
       // Merges two PDF document into a third PDF document.
       ImGearPDFDocument MergePdfDocuments(ImGearPDFDocument igFirstDocument, ImGearPDFDocument igSecondDocument)
       {
           // ImageGear uses zero-based numeration of pages in document.
           int FIRST_PAGE_INDEX = 0;

           // Create new PDF document for result.
           ImGearPDFDocument igResultDocument = new ImGearPDFDocument();

           // Copy all pages of first document into result document.
           for (int pageIndex = FIRST_PAGE_INDEX; pageIndex < igFirstDocument.Pages.Count; pageIndex++)
               igResultDocument.Pages.Add(igFirstDocument.Pages[pageIndex].Clone());

           // Copy all pages of second document into result document.
           for (int pageIndex = FIRST_PAGE_INDEX; pageIndex < igSecondDocument.Pages.Count; pageIndex++)
               igResultDocument.Pages.Add(igSecondDocument.Pages[pageIndex].Clone());
           return igResultDocument;
       }
VB.NET
Copy Code
Imports ImageGear.Formats.PDF
' Merges two PDF document into third PDF document.
Private Function MergePdfDocuments(igFirstDocument As ImGearPDFDocument, igSecondDocument As ImGearPDFDocument) As ImGearPDFDocument

   ' ImageGear uses zero-based numeration of pages in document.
   Dim FIRST_PAGE_INDEX As Integer
   FIRST_PAGE_INDEX = 0

   ' Create new PDF document for result.
   Dim igResultDocument As New ImGearPDFDocument()

   ' Copy all pages of first document into result document.
    Dim pageIndex As Integer = FIRST_PAGE_INDEX
    While pageIndex < igFirstDocument.Pages.Count
       igResultDocument.Pages.Add(igFirstDocument.Pages(pageIndex).Clone())
       System.Math.Max(System.Threading.Interlocked.Increment(pageIndex), pageIndex - 1)
    End While

    ' Copy all pages of second document into result document.
    pageIndex = FIRST_PAGE_INDEX
    While pageIndex < igSecondDocument.Pages.Count
       igResultDocument.Pages.Add(igSecondDocument.Pages(pageIndex).Clone())
       System.Math.Max(System.Threading.Interlocked.Increment(pageIndex), pageIndex - 1)
    End While

    Return igResultDocument

End Function

This method can be extended for any document type. The main rule that must be observed for copying pages from one document to another is that the type of the documents must be the same.

Is this page helpful?
Yes No
Thanks for your feedback.