Skip to footer content
USING IRONPDF

How to Merge Two PDF Byte Arrays in C#

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.

How to Merge Two PDF Byte Arrays in C# Using IronPDF: Image 1 - IronPDF

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 Merge Two PDF Byte Arrays in C# Using IronPDF: Image 2 - Features

How to Set Up IronPDF for Merging PDFs?

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

Install-Package IronPdf

How to Merge Two PDF Byte Arrays in C# Using IronPDF: Image 3 - Installation Add from PixabayUpload

or drag and drop an image here

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:

IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"
$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# Using IronPDF: Image 4 - Cross-platform compatibility

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

var PDF = PdfDocument.Merge(
    PdfDocument.FromBytes(pdfBytes1),
    PdfDocument.FromBytes(pdfBytes2));
var PDF = PdfDocument.Merge(
    PdfDocument.FromBytes(pdfBytes1),
    PdfDocument.FromBytes(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);
    // 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);
    // 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.FromBytes() method loads each byte array into PdfDocument objects. The Merge() method combines both PDF documents into a single new PDF, preserving all content, formatting, and form fields.

Input

How to Merge Two PDF Byte Arrays in C# Using IronPDF: Image 5 - Sample PDF Input 1

How to Merge Two PDF Byte Arrays in C# Using IronPDF: Image 6 - Sample PDF Input 2

Output

How to Merge Two PDF Byte Arrays in C# Using IronPDF: Image 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 Two PDF Byte Arrays in C# Using IronPDF: Image 8 - Async Merge PDF Output

How to Merge Multiple PDF Files Efficiently?

When working with multiple PDF files, use a List for batch processing. Basically, 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 page 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 Two PDF Byte Arrays in C# Using IronPDF: Image 9 - How to Merge two PDF byte arrays in C# - IronPDF

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.

How to Merge Two PDF Byte Arrays in C# Using IronPDF: Image 10 - Licensing

Frequently Asked Questions

How can I merge two PDF byte arrays in C#?

You can merge two PDF byte arrays in C# using IronPDF. It allows you to easily combine multiple PDF files stored as byte arrays into a single PDF document without the need to save them to disk.

What are the benefits of using IronPDF for merging PDF byte arrays?

IronPDF simplifies the process of merging PDF byte arrays by providing an intuitive API. It handles PDFs efficiently in memory, which is ideal for applications that retrieve PDFs from databases or web services.

Can IronPDF merge PDF files without saving them to disk?

Yes, IronPDF can merge PDF files without saving them to disk. It processes PDF files directly from byte arrays, making it suitable for memory-based operations.

Is it possible to merge PDF files received from web services using IronPDF?

Absolutely. IronPDF can merge PDF files received as byte arrays from web services, allowing seamless integration with remote PDF sources.

What is a common application of merging PDF byte arrays in C#?

A common application is combining multiple PDF documents retrieved from a database into a single PDF file before processing or displaying it in a C# application.

Does IronPDF support processing PDFs in memory?

Yes, IronPDF supports processing PDFs in memory, which is essential for applications that require rapid manipulation of PDF files without intermediate disk storage.

How does IronPDF handle PDF merging from databases?

IronPDF handles PDF merging from databases by allowing you to directly work with PDF byte arrays, eliminating the need for temporary file storage.

Can IronPDF combine multiple PDF files into one?

Yes, IronPDF can combine multiple PDF files into one by merging their byte arrays, providing a streamlined method for creating composite PDF documents.

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