DEV Community

Ali Jago Seif
Ali Jago Seif

Posted on

1 2

Merge PDF files in C#

In this article, I am going to show you how to merge multiple PDF files programmatically using Merge_File method and easy PDF SDK. This C# sample program demonstrates how to merge PDF pages using the PDFProcessor API.

The file names are assumed to be in the array files[]. The merged file is saved under “outFileName”

private void Merge_File(string[] files, string outFileName)
{
    try
    {
        PDFProcessor oPDFProcessor = new PDFProcessor();
            // loop over all the files, which are concatenated one by one
            string inFileName = files[0];
    
        for(int i = 1; i < files.Length; i++)
        {
            oPDFProcessor.Merge(inFileName, files[i], outFileName);         
            inFileName = outFileName;
        }               
            
        MessageBox.Show(files.Length.ToString() + " files merged!");
    }
    catch(System.Runtime.InteropServices.COMException err)
    {
        MessageBox.Show(err.Message + " (" + err.ErrorCode.ToString() + ")");
    }
}

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (1)

Collapse
 
atir_tahir profile image
Atir Tahir

This is quite helpful but what if we want one-stop solution for different file formats. Like if I want to merge Word files or Excel files using single API? At this point, GroupDocs.Merger for .NET API allows you to join two Word files or two Excel spreadsheet etc using same piece of code.
See how simple is this:

// For complete examples and data files, please go to https://github.com/groupdocs-merger/GroupDocs.Merger-for-.NET
string sourceFile1 = CommonUtilities.fileOne + fileOne;
string sourceFile2 = CommonUtilities.fileTwo + fileTwo;
// Preparing.
Stream openFile1 = new FileStream(sourceFile1, FileMode.Open);
Stream openFile2 = new FileStream(sourceFile2, FileMode.Open);
List<Stream> documentStreams = new List<Stream>();
documentStreams.Add(openFile1);
documentStreams.Add(openFile2);
// Main method.
DocumentResult result = new DocumentHandler().Join(documentStreams);
Stream documentStream = result.Stream;
var fileStream = File.Create(CommonUtilities.outputPath + "OutPut." + result.FileFormat);
documentStream.CopyTo(fileStream);
documentStream.Close();

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay