Skip to footer content
USING IRONPDF

How to Merge PDF Byte Arrays in C#

Merging PDF Files Programmatically with IronPDF

Working with PDF files in memory is a common requirement in modern .NET applications. Whether you're receiving multiple PDF files from web APIs, retrieving them from database BLOB columns, or processing uploaded files from your server, you often need to combine multiple PDF byte arrays into a single PDF document without touching the file system. In this article, we will learn how IronPDF makes PDF merging remarkably straightforward with its intuitive API for merging PDFs programmatically.

Why Can't You Simply Concatenate PDF File Byte Arrays?

Unlike text files, PDF documents have a complex internal structure with cross-reference tables, object definitions, and specific formatting requirements. Simply concatenating two PDF files as byte arrays would corrupt the document structure, resulting in an unreadable PDF file. This is why specialized PDF libraries like IronPDF are essential — they understand the PDF specification and properly merge PDF files while maintaining their integrity. According to Stack Overflow forum discussions, attempting direct byte array concatenation is a common error developers make when trying to merge PDF content.

How to Set Up IronPDF for Merging PDFs

Install IronPDF through NuGet Package Manager in your .NET project:

Install-Package IronPdf

Add the necessary using statements to import the library:

using IronPdf;
using System.IO;  // For MemoryStream
using System.Threading.Tasks;
using IronPdf;
using System.IO;  // For MemoryStream
using System.Threading.Tasks;
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

For production server environments, apply your license key to access full features without password restrictions:

License.LicenseKey = "YOUR-LICENSE-KEY";
License.LicenseKey = "YOUR-LICENSE-KEY";
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

IronPDF supports Windows, Linux, macOS, and Docker containers, making it a practical solution for ASP.NET Core and cloud-native applications.

How to Merge Two PDF Byte Arrays in C# with IronPDF

var pdf = PdfDocument.Merge(
    PdfDocument.FromFile(pdfBytes1), 
    PdfDocument.FromFile(pdfBytes2));
var pdf = PdfDocument.Merge(
    PdfDocument.FromFile(pdfBytes1), 
    PdfDocument.FromFile(pdfBytes2));
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Here's the core code sample for merging two PDF files from byte array data:

public byte[] MergePdfByteArrays(byte[] firstPdf, byte[] secondPdf)
{
    // Load the first PDF file from byte array
    var pdf1 = new PdfDocument(firstPdf /* PdfData */, /* password: */ "", /* ownerPassword: */ "");
    // Load the second PDF file from byte array  
    var pdf2 = new PdfDocument(secondPdf, "", "");
    // Merge PDF documents into one PDF
    var mergedPdf = PdfDocument.Merge(pdf1, pdf2);
    // Return the combined PDF as byte array
    return mergedPdf.BinaryData;
}
public byte[] MergePdfByteArrays(byte[] firstPdf, byte[] secondPdf)
{
    // Load the first PDF file from byte array
    var pdf1 = new PdfDocument(firstPdf /* PdfData */, /* password: */ "", /* ownerPassword: */ "");
    // Load the second PDF file from byte array  
    var pdf2 = new PdfDocument(secondPdf, "", "");
    // Merge PDF documents into one PDF
    var mergedPdf = PdfDocument.Merge(pdf1, pdf2);
    // Return the combined PDF as byte array
    return mergedPdf.BinaryData;
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This method accepts two PDF byte arrays as input parameters. The PdfDocument.FromFile() method loads each byte array into PdfDocument objects; despite its name, this method handles byte arrays perfectly. The Merge() method combines both PDF documents into a single new PDF, preserving all content, formatting, and form fields.

Input

How to Merge PDF Byte Arrays in C#: Figure 5 - Sample PDF Input 1

How to Merge PDF Byte Arrays in C#: Figure 6 - Sample PDF Input 2

Output

How to Merge PDF Byte Arrays in C#: Figure 7 - Merge two PDF Byte Arrays Output

For more control, you can also work with a new MemoryStream directly:

public byte[] MergePdfsWithStream(byte[] src1, byte[] src2)
{
    using (var stream = new MemoryStream())
    {
        var pdf1 = new PdfDocument(src1);
        var pdf2 = new PdfDocument(src2);
        var combined = PdfDocument.Merge(pdf1, pdf2);
        return combined.BinaryData;
    }
}
public byte[] MergePdfsWithStream(byte[] src1, byte[] src2)
{
    using (var stream = new MemoryStream())
    {
        var pdf1 = new PdfDocument(src1);
        var pdf2 = new PdfDocument(src2);
        var combined = PdfDocument.Merge(pdf1, pdf2);
        return combined.BinaryData;
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

If both PDF files contain form fields with identical names, IronPDF automatically handles naming conflicts by appending underscores. Finally, the BinaryData property returns the combined PDF as a new document in byte array format. To pass the result to other methods, simply return this byte array — no need to save to disk unless required.

How to Implement Async Merging for Better Performance

For applications handling large PDF files or high request volumes on your server, async operations prevent thread blocking. The following code shows how to merge PDF documents asynchronously:

public async Task<byte[]> MergePdfByteArraysAsync(byte[] firstPdf, byte[] secondPdf)
{
    return await Task.Run(() =>
    {
        var pdf1 = new PdfDocument(firstPdf);
        var pdf2 = new PdfDocument(secondPdf);
        var pdf = PdfDocument.Merge(pdf1, pdf2);
        return pdf.BinaryData;
    });
}
public async Task<byte[]> MergePdfByteArraysAsync(byte[] firstPdf, byte[] secondPdf)
{
    return await Task.Run(() =>
    {
        var pdf1 = new PdfDocument(firstPdf);
        var pdf2 = new PdfDocument(secondPdf);
        var pdf = PdfDocument.Merge(pdf1, pdf2);
        return pdf.BinaryData;
    });
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This async implementation wraps the PDF merging operation in Task.Run(), allowing it to execute on a background thread. This approach is particularly valuable in ASP.NET web applications where you want to maintain responsive request handling while processing multiple PDF documents. The method returns a Task<byte[]>, enabling callers to await the result without blocking the main thread. The above code ensures efficient memory management when dealing with large PDF file operations.

Output

How to Merge PDF Byte Arrays in C#: Figure 8 - Async Merge PDF Output

How to Merge Multiple PDF Files Efficiently

When working with multiple PDF files, use a List for batch processing. This solution allows you to combine any number of PDF documents into one PDF:

public byte[] MergeMultiplePdfByteArrays(List<byte[]> pdfByteArrays)
{
    if (pdfByteArrays == null || pdfByteArrays.Count == 0)
        return null;
    // Convert all byte arrays to PdfDocument objects
    var pdfDocuments = pdfByteArrays
        .Select(bytes => new PdfDocument(bytes))
        .ToList();
    // Merge all PDFs in one operation
    var pdf = PdfDocument.Merge(pdfDocuments);
    // Clean up resources
    foreach (var pdfDoc in pdfDocuments)
    {
        pdfDoc.Dispose();
    }
    return pdf.BinaryData;
}
public byte[] MergeMultiplePdfByteArrays(List<byte[]> pdfByteArrays)
{
    if (pdfByteArrays == null || pdfByteArrays.Count == 0)
        return null;
    // Convert all byte arrays to PdfDocument objects
    var pdfDocuments = pdfByteArrays
        .Select(bytes => new PdfDocument(bytes))
        .ToList();
    // Merge all PDFs in one operation
    var pdf = PdfDocument.Merge(pdfDocuments);
    // Clean up resources
    foreach (var pdfDoc in pdfDocuments)
    {
        pdfDoc.Dispose();
    }
    return pdf.BinaryData;
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This method efficiently handles any number of PDF byte arrays. It first validates the input to ensure the list contains data. Using LINQ's Select() method, it transforms each byte array into PdfDocument objects. The Merge() method accepts a List of PdfDocument objects, combining them all in a single operation to create a new document. Resource cleanup is important — disposing of individual PdfDocument objects after PDF merging helps manage memory and resources effectively, especially when processing numerous or large PDF files. The length of the resulting byte array depends on the pages in all source PDF documents.

What Are the Best Practices for Production Use?

Always wrap PDF operations in try-catch blocks to handle potential exceptions from corrupted or password-protected PDF files. Use using statements or explicitly dispose of PdfDocument objects to prevent memory leaks. For large-scale operations, consider implementing pagination or streaming approaches rather than loading entire documents into memory simultaneously.

When working with selected pages from multiple PDF documents, you can also extract specific PdfPage instances before merging. IronPDF's comprehensive error handling ensures robust production deployments in both test and production environments. If you're familiar with other PDF libraries, you'll find IronPDF's API particularly intuitive to import and use in your project.

How to Merge PDF Byte Arrays in C#: Figure 9

Conclusion

IronPDF simplifies the complex task of merging PDF files from byte arrays in C#, providing a clean API that handles the intricate details of PDF document structure automatically. Whether you're building document management systems, processing API responses, handling file uploads with attachments, or working with database storage, IronPDF's merge PDF capabilities integrate seamlessly into your .NET applications.

The library supports async operations and memory-efficient processing, making it a practical solution for both desktop and server applications. You can edit, convert, and save PDF files without writing temporary files to disk. For those looking to post questions or find additional answers, visit our forum or website.

Ready to download and implement PDF merging in your application? Get started with a free trial or explore the comprehensive API documentation to discover IronPDF's full feature set, including HTML to PDF conversion, PDF forms handling, and digital signatures. Our site provides complete reference documentation for all System.IO stream operations.

Licensing

Frequently Asked Questions

How can I merge PDF byte arrays using C#?

You can merge PDF byte arrays in C# by utilizing IronPDF. The library provides a straightforward method to combine multiple PDF files programmatically, allowing for efficient handling of PDF documents.

What are the benefits of using IronPDF for merging PDFs?

IronPDF simplifies the process of merging PDFs by offering robust and easy-to-use tools. It supports various functions such as merging, splitting, and modifying PDFs, making it an ideal choice for developers working with PDF documents in C#.

Is it possible to merge PDF files without saving them as physical files?

Yes, IronPDF allows you to merge PDF files directly in memory without the need to save them as physical files, using byte arrays to handle PDF data efficiently.

Can IronPDF handle large PDF files when merging?

IronPDF is designed to efficiently handle large PDF files during the merging process, ensuring that developers can work with extensive documents without facing performance issues.

What programming environments are supported for merging PDFs with IronPDF?

IronPDF supports various .NET environments, including C#, making it versatile for developers working within different programming setups to merge PDFs seamlessly.

Does IronPDF support merging encrypted PDF files?

Yes, IronPDF can handle encrypted PDF files, providing options to merge and manipulate them as long as the necessary permissions and credentials are provided.

How does IronPDF ensure the integrity of merged PDF documents?

IronPDF maintains the original quality and format of the merged PDF documents, ensuring that the integrity and appearance of the files are preserved throughout the merging process.

Can IronPDF merge PDFs with different page sizes and orientations?

IronPDF is capable of merging PDFs with varying page sizes and orientations, automatically adjusting the final document to maintain a consistent and professional layout.

What are the prerequisites for using IronPDF to merge PDF byte arrays?

To use IronPDF for merging PDF byte arrays, you need to have a .NET development environment set up and the IronPDF library installed in your project.

Are there any examples or documentation available for using IronPDF?

Comprehensive documentation and examples are available on the IronPDF website, providing step-by-step guides and code snippets for various functionalities, including merging PDF byte arrays.

Curtis Chau
Technical Writer

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.

...

Read More