ImageGear for C and C++ on Linux v18.8 - Updated
Merge Multiple PDFs
User Guide > How to Work with... > Formats with Additional Functionality > PDF > How to... > Merge Multiple PDFs

Before working with a PDF document, make sure to initialize the PDF component (see Getting Started with PDF).

This section illustrates how to merge two PDF documents into one document. This example assumes you have two loaded HMIGEAR PDF documents in memory, i.e., document1 and document2 (refer to Load and Save a PDF to learn how to load a PDF).

Refer to the PDFMerge Sample for complete sample code that illustrates how to use this capability.

  1. Create handles to PDF document objects, using the information from each loaded HMIGEAR object:
    C and C++
    Copy Code
       HIG_PDF_DOC pdf1 = 0;
       HIG_PDF_DOC pdf2 = 0;
       IG_mpi_info_get(document1, IG_MP_DOCUMENT, &pdf1, sizeof(HIG_PDF_DOC));
       IG_mpi_info_get(document2, IG_MP_DOCUMENT, &pdf2, sizeof(HIG_PDF_DOC));
    
  2. Create the target PDF document in which to insert the PDF pages:
    C and C++
    Copy Code
       HMIGEAR targetDocument = 0;
       HIG_PDF_DOC targetPdf = 0;
       IG_mpi_create(&targetDocument, 0);
       IG_PDF_doc_create(targetDocument);
       IG_mpi_info_get(targetDocument, IG_MP_DOCUMENT, &targetPdf, sizeof(HIG_PDF_DOC));
    

    At this point, the target PDF document has zero pages.

  3. Append all pages from each source PDF document:
    C and C++
    Copy Code
       UINT firstPage = 0;
       IG_PDF_doc_insert_pages(targetPdf, IG_PDF_LAST_PAGE, pdf1, firstPage,
               IG_PDF_ALL_PAGES, IG_PDF_INSERT_ALL);
       IG_PDF_doc_insert_pages(targetPdf, IG_PDF_LAST_PAGE, pdf2, firstPage,
               IG_PDF_ALL_PAGES, IG_PDF_INSERT_ALL);
    
  4. Save the merged PDF to disk:
    C and C++
    Copy Code
       UINT pageCount = 0;
       IG_PDF_doc_get_page_count(targetPdf, &pageCount);
       IG_mpi_file_save("merged.pdf", targetDocument, firstPage, firstPage, pageCount, IG_FORMAT_PDF,
               IG_MPI_SAVE_OVERWRITE);