Skip to Main Content

How to Split and Merge PDF Documents in C# with ImageGear

Today’s organizations are inundated with a variety of document and image formats on a regular basis. By integrating comprehensive PDF functionality into their applications, developers can provide the tools to manage those files much more easily. Converting files into PDFs makes them easier to share, modify, and annotate without having to worry about compatibility issues across applications.

Simply converting documents or images into searchable PDF files is easy enough, but in many cases, several files need to be merged into a single document or one large file must be split into multiple documents. Accusoft’s ImageGear SDK gives applications the ability to process PDFs programmatically, allowing users to quickly prepare documents for viewing and collaboration.

How to Merge PDF Files with ImageGear Using C#

ImageGear can merge two multi-page PDF documents into a single document. This is especially useful for organizations that have multiple files associated with the same workflow or account, such as loan applications or medical records. The following steps will walk you through the merge PDF process using ImageGear.NET in C#.

Step 1: Initialize PDF Support

Before getting started, you’ll need to initialize PDF support within ImageGear.NET (if you haven’t done so already during deployment). This initialization will allow your application to load, save, and process PDF files.

After creating a new “Console Application” and adding the required assembly reference and resources, you can use the following code snippet to load and save PDF files.

 

using System.IO;
using ImageGear.Formats;
using ImageGear.Formats.PDF;
using ImageGear.Evaluation;
namespace MyPDFProject
{
    class Program
    {
        public void Initialize()
        {
            // Initialize evaluation license.
            ImGearEvaluationManager.Initialize();
            ImGearEvaluationManager.Mode = ImGearEvaluationMode.Watermark;
            // Initialize common formats.
            ImGearCommonFormats.Initialize();
            // Add support for PDF files.
            ImGearFileFormats.Filters.Insert(0, ImGearPDF.CreatePDFFormat());
            ImGearPDF.Initialize();
        }
        public void Terminate()
        {
            // Dispose of support for PDF files.
            ImGearPDF.Terminate();
        }
        public void LoadAndSave(string fileIn, string fileOut)
        {
            ImGearPDFDocument igPDFDocument = null;
            try
            {
                // Load the PDF document.
                using (FileStream inStream = new FileStream(fileIn, FileMode.Open))
                    igPDFDocument = (ImGearPDFDocument)ImGearFileFormats.LoadDocument(inStream, 0, (int)ImGearPDFPageRange.ALL_PAGES);
                // Save the PDF document to a new file.
                ImGearPDFSaveOptions pdfOptions = new ImGearPDFSaveOptions();
                using (FileStream outStream = new FileStream(fileOut, FileMode.Create))
                    ImGearFileFormats.SaveDocument(igPDFDocument, outStream, 0, ImGearSavingModes.OVERWRITE, ImGearSavingFormats.PDF, pdfOptions);
            }
            finally
            {
                igPDFDocument?.Dispose();
            }
        }
        static void Main(string[] args)
        {
            Program myProgram = new Program();
            myProgram.Initialize();
            myProgram.LoadAndSave(@"C:\PATHTOPDF\FILENAME.pdf", @"C:\PATHTOPDF\NEWNAME.pdf");
            myProgram.Terminate();
        }
    }
}

       

 

Step 2: Set the Merge PDF Parameters

You will need to determine what order the documents will be combined in and set the page numeration for the new document.

Step 3: Merge the PDF Documents

Once you’ve identified the files you want to merge and the order they should go in, you can use the “MergePdfDocuments” command to assemble the new PDF file. Here’s what the code snippet looks like in C#:

 

        // Merges two PDF document into a third PDF document.
        public void Merge(string fileInFirst, string fileInSecond, string fileOut)
        {
            // ImageGear uses zero-based page numbers.
            const int FIRST_PAGE_INDEX = 0;
            ImGearPDFDocument igPDFDocumentFirst = null;
            ImGearPDFDocument igPDFDocumentSecond = null;
            ImGearPDFDocument igPDFDocumentResult = null;
            try
            {
                // Load the source PDF documents.
                using (FileStream inStream = new FileStream(fileInFirst, FileMode.Open))
                    igPDFDocumentFirst = (ImGearPDFDocument)ImGearFileFormats.LoadDocument(inStream, 0, (int)ImGearPDFPageRange.ALL_PAGES);
                using (FileStream inStream = new FileStream(fileInSecond, FileMode.Open))
                    igPDFDocumentSecond = (ImGearPDFDocument)ImGearFileFormats.LoadDocument(inStream, 0, (int)ImGearPDFPageRange.ALL_PAGES);
                // Create the resulting PDF document.
                igPDFDocumentResult = new ImGearPDFDocument();
                // Copy all pages of first document into resulting PDF document.
                for (int pageIndex = FIRST_PAGE_INDEX; pageIndex < igPDFDocumentFirst.Pages.Count; pageIndex++)
                    igPDFDocumentResult.Pages.Add(igPDFDocumentFirst.Pages[pageIndex].Clone());
                // Copy all pages of second document into resulting PDF document.
                for (int pageIndex = FIRST_PAGE_INDEX; pageIndex < igPDFDocumentSecond.Pages.Count; pageIndex++)
                    igPDFDocumentResult.Pages.Add(igPDFDocumentSecond.Pages[pageIndex].Clone());
                // Save the resulting PDF document to a new file.
                ImGearPDFSaveOptions pdfOptions = new ImGearPDFSaveOptions();
                using (FileStream outStream = new FileStream(fileOut, FileMode.Create))
                    ImGearFileFormats.SaveDocument(igPDFDocumentResult, outStream, 0, ImGearSavingModes.OVERWRITE, ImGearSavingFormats.PDF, pdfOptions);
            }
            finally
            {
                igPDFDocumentFirst?.Dispose();
                igPDFDocumentSecond?.Dispose();
                igPDFDocumentResult?.Dispose();
            }
        }
        static void Main(string[] args)
        {
            Program myProgram = new Program();
            myProgram.Initialize();
            myProgram.Merge(@"C:\PATHTOPDF\FIRSTFILENAME.pdf", @"C:\PATHTOPDF\SECONDFILENAME.pdf", @"C:\PATHTOPDF\NEWNAME.pdf");
            myProgram.Terminate();
        }

 

After merging your files into a new document, you can begin working with the resulting PDF using ImageGear’s other PDF features:

How to Split PDF Files with ImageGear Using C#

While the merge PDF command is used to combine multiple documents into a new, single PDF file, the split PDF command saves pages from an existing document as a separate document. A three-page PDF file, for instance, can be broken into three, single-page PDF documents.

Once you’ve initialized PDF support for ImageGear.NET, you can split a PDF document by following a few simple steps:

Step 1: Read the PDF into a System.IO.Stream Object

This allows ImageGear to read the stream using ImGearFileFormats.LoadDocument(FILE NAME) command.

Step 2: Determine PDF Page Count

The ImGearPDFDocument.Pages property provides access to the document’s page array, which can then be used to assemble a new document.

Step 3: Create a New PDF Document

The ImGearPDFDocument object can be used to create an empty PDF document that will serve as the destination file for the split pages.

Step 4: Insert Pages into the New Document

The InsertPages command takes specific pages from the source document (the PDF you’re splitting), and inserts them into the destination document. After the pages are inserted, you can save the new PDF to disk or memory. Keep in mind that the original document will still contain all pages, so splitting it into two documents will require you to create two new documents.

Here is a what splitting a single PDF document into several single-page PDF documents looks like in C#:

 

public void Split(string fileIn, string directoryOut)
        {
            // ImageGear uses zero-based page numbers.
            const int FIRST_PAGE = 0;
            // Ensure output directory exists.
            if (!System.IO.Directory.Exists(directoryOut))
                Directory.CreateDirectory(directoryOut);
            // Load the source PDF document.
            using (FileStream inStream = new FileStream(fileIn, FileMode.Open))
            {
                using (ImGearPDFDocument igPDFDocument = ImGearFileFormats.LoadDocument(inStream, FIRST_PAGE, (int)ImGearPDFPageRange.ALL_PAGES) as ImGearPDFDocument)
                {
                    // Write each page in source PDF document to a separate PDF file.
                    for (int pageIndex = FIRST_PAGE; pageIndex < igPDFDocument.Pages.Count; pageIndex++)
                    {
                        // Construct the output filepath.
                        string outputFileName = string.Format("{0}_{1}.pdf", Path.GetFileNameWithoutExtension(fileIn), pageIndex + 1);
                        string outputPath = System.IO.Path.Combine(directoryOut, outputFileName);
                        // Create a new empty PDF document.
                        using (ImGearPDFDocument igPDFDocumentResult = new ImGearPDFDocument())
                        {
                            // Insert page into new PDF document.
                            igPDFDocumentResult.InsertPages((int)ImGearPDFPageNumber.BEFORE_FIRST_PAGE, igPDFDocument, pageIndex, 1, ImGearPDFInsertFlags.DEFAULT);
                            // Save new PDF document to file.
                            igPDFDocumentResult.Save(outputPath, ImGearSavingFormats.PDF, FIRST_PAGE, FIRST_PAGE, 1, ImGearSavingModes.OVERWRITE);
                        }
                    }
                }
            }
        }
        static void Main(string[] args)
        {
            Program myProgram = new Program();
            myProgram.Initialize();
            myProgram.Split(@"C:\PATHTOPDF\FILENAME.pdf", @"C:\PATHTOPDF\OUTPUTDIRECTORY");
            myProgram.Terminate();
        }

 

Enhance Your PDF Capabilities with ImageGear

Accusoft’s ImageGear SDK provides a broad range of document and image processing functions beyond the ability to split and merge PDFs. Whether you need powerful file conversion capabilities, multi-language OCR support, or image cleanup, correction, and transformation functions, ImageGear integrations can enhance your application’s performance and versatility. 

Learn more about the ImageGear collection of SDKs and see how they can help you shorten your development cycle and get your innovative products to market faster.