Skip to footer content
USING IRONPDF

How to Merge Two PDF Byte Arrays in C#

Working with PDF files stored as byte arrays is a common requirement in modern C# applications. Whether you're retrieving PDF documents from a database, receiving them from web services, or processing them in memory, the ability to merge multiple PDF files into one PDF without saving to disk is essential.

IronPDF makes this process remarkably simple with its intuitive API. You can easily combine two PDF files or many, and achieve your requirement of creating a combined PDF as a single PDF output. Follow along as we look at how you can merge PDF byte arrays in C# and the different approaches for this task.

What Are PDF Byte Arrays and Why Merge Them?

A byte array is basically raw binary data representing a PDF file in memory. When working with PDF documents in C#, you'll often encounter scenarios where PDF files exist as byte arrays rather than physical files on disk. This is particularly common when retrieving documents from databases where PDFs are stored as binary data, or when receiving PDF documents from REST APIs via the server.

Simply concatenating two PDF byte arrays won't work—unlike text files, PDF files have complex internal structures with headers, cross-reference tables, and specific formatting. If you just try to join the bytes, you will certainly get an error. You need a proper PDF library to parse these byte arrays and combine them correctly. IronPDF handles all this complexity, allowing you to merge PDF documents with just a few lines of code. This is the core problem the library helps you understand and solve.

How Do I Set Up IronPDF for PDF Merging?

Getting started with IronPDF is straightforward. First, install the IronPDF NuGet package in your project:

Install-Package IronPdf

Once installed, add the following namespaces to your C# file:

using IronPdf;
using System.IO;
using System.Collections.Generic;
using IronPdf;
using System.IO;
using System.Collections.Generic;
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

It's important to understand the system and path requirements to handle the files correctly. We can use this code in ASP applications or desktop applications.

How to Merge Two PDF Byte Arrays in C#: Figure 1 - IronPDF NuGet Installation page

How Can I Merge Two PDF File Byte Arrays Using IronPDF?

Here's a complete example demonstrating how to merge two PDF byte arrays in C# into a single PDF:

// Simulate two PDF byte arrays (in practice, these come from a database or API)
byte[] pdfBytes1 = File.ReadAllBytes("document1.pdf");
byte[] pdfBytes2 = File.ReadAllBytes("document2.pdf");

// Create PdfDocument objects from byte arrays
var pdf1 = new PdfDocument(pdfBytes1);
var pdf2 = new PdfDocument(pdfBytes2);

// Merge the two PDF documents
PdfDocument combinedPdf = PdfDocument.Merge(pdf1, pdf2);

// Convert the combined PDF back to byte array
byte[] mergedPdfBytes = combinedPdf.BinaryData;

// Save the merged PDF (optional)
File.WriteAllBytes("merged.pdf", mergedPdfBytes);
// Simulate two PDF byte arrays (in practice, these come from a database or API)
byte[] pdfBytes1 = File.ReadAllBytes("document1.pdf");
byte[] pdfBytes2 = File.ReadAllBytes("document2.pdf");

// Create PdfDocument objects from byte arrays
var pdf1 = new PdfDocument(pdfBytes1);
var pdf2 = new PdfDocument(pdfBytes2);

// Merge the two PDF documents
PdfDocument combinedPdf = PdfDocument.Merge(pdf1, pdf2);

// Convert the combined PDF back to byte array
byte[] mergedPdfBytes = combinedPdf.BinaryData;

// Save the merged PDF (optional)
File.WriteAllBytes("merged.pdf", mergedPdfBytes);
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output

How to Merge Two PDF Byte Arrays in C#: Figure 2 - Merged PDF files

The code above demonstrates the core merging functionality. First, we create PdfDocument objects from our byte arrays. IronPDF automatically handles parsing the binary data and creating proper PDF document objects.

The PdfDocument.Merge() method combines multiple PDF files into one PDF, preserving all pages, formatting, and content from both source documents. Finally, we can access the merged document as a byte array using the BinaryData property, perfect for saving to a database or sending via an API. The process of taking the bytes and converting them into a new PDF is done by the library, providing us with a new document.

What Alternative Methods Exist for Merging PDFs?

IronPDF provides flexible options for merging PDF documents. When you need to merge more than two PDF files, you can use the List overload. This approach is shown below:

// Define pdfByteArrays as a list of byte arrays
List<byte[]> pdfByteArrays = new List<byte[]>
{
    // Add sample byte arrays representing PDFs
    File.ReadAllBytes("example1.pdf"),
    File.ReadAllBytes("example2.pdf")
};

List<PdfDocument> pdfsToMerge = new List<PdfDocument>();
foreach (var byteArray in pdfByteArrays)
{
    pdfsToMerge.Add(new PdfDocument(byteArray));
}

PdfDocument combinedPdf = PdfDocument.Merge(pdfsToMerge);
byte[] finalPdfBytes = combinedPdf.BinaryData;
// Define pdfByteArrays as a list of byte arrays
List<byte[]> pdfByteArrays = new List<byte[]>
{
    // Add sample byte arrays representing PDFs
    File.ReadAllBytes("example1.pdf"),
    File.ReadAllBytes("example2.pdf")
};

List<PdfDocument> pdfsToMerge = new List<PdfDocument>();
foreach (var byteArray in pdfByteArrays)
{
    pdfsToMerge.Add(new PdfDocument(byteArray));
}

PdfDocument combinedPdf = PdfDocument.Merge(pdfsToMerge);
byte[] finalPdfBytes = combinedPdf.BinaryData;
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This approach allows you to merge any number of PDF documents efficiently. Each PDF is loaded from its byte array into a PdfDocument object, added to a list, and then merged in a single operation.

Using MemoryStream for Flexibility

You can also use MemoryStream for more control over the process when handling streams. The following code demonstrates this approach:

using (var stream1 = new MemoryStream(pdfBytes1))
using (var stream2 = new MemoryStream(pdfBytes2))
{
    var pdf1 = new PdfDocument(stream1);
    var pdf2 = new PdfDocument(stream2);
    var merged = PdfDocument.Merge(pdf1, pdf2);
    byte[] result = merged.BinaryData;
}
using (var stream1 = new MemoryStream(pdfBytes1))
using (var stream2 = new MemoryStream(pdfBytes2))
{
    var pdf1 = new PdfDocument(stream1);
    var pdf2 = new PdfDocument(stream2);
    var merged = PdfDocument.Merge(pdf1, pdf2);
    byte[] result = merged.BinaryData;
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Working with streams provides better memory management for larger PDF files and gives you more flexibility when integrating with other systems that use stream-based I/O. This example is a fantastic way of using the stream effectively. The Length property can be checked on the stream if needed.

How Do I Handle Common PDF Document Merging Scenarios?

For a typical scenario where you're fetching PDFs from a database and need to combine them:

public string MergePdfDocumentsFromDatabase(List<int> documentIds)
{
    List<PdfDocument> documents = new List<PdfDocument>();

    foreach (int id in documentIds)
    {
        // Fetch PDF byte array from database
        byte[] pdfData = GetPdfFromDatabase(id); // Assume this function exists
        documents.Add(new PdfDocument(pdfData));
    }

    // Merge all documents
    PdfDocument mergedDocument = PdfDocument.Merge(documents);

    // The document is saved back to a stream or to the server
    byte[] resultBytes = mergedDocument.BinaryData;

    // For this example, we return a success string
    return "Merge True: Document successfully combined and saved.";
}

public PdfDocument AddPageToPdf(PdfDocument existingDoc, byte[] newPageBytes)
{
    // Create a PdfDocument object from the new page bytes
    using var stream = new MemoryStream(newPageBytes);
    var newPageDoc = new PdfDocument(stream);

    // Get the first page of the new document
    var newPage = newPageDoc.Pages[0];

    // Add the page to the existing document
    existingDoc.Pages.Add(newPage);

    // Return the modified document
    return existingDoc;
}
public string MergePdfDocumentsFromDatabase(List<int> documentIds)
{
    List<PdfDocument> documents = new List<PdfDocument>();

    foreach (int id in documentIds)
    {
        // Fetch PDF byte array from database
        byte[] pdfData = GetPdfFromDatabase(id); // Assume this function exists
        documents.Add(new PdfDocument(pdfData));
    }

    // Merge all documents
    PdfDocument mergedDocument = PdfDocument.Merge(documents);

    // The document is saved back to a stream or to the server
    byte[] resultBytes = mergedDocument.BinaryData;

    // For this example, we return a success string
    return "Merge True: Document successfully combined and saved.";
}

public PdfDocument AddPageToPdf(PdfDocument existingDoc, byte[] newPageBytes)
{
    // Create a PdfDocument object from the new page bytes
    using var stream = new MemoryStream(newPageBytes);
    var newPageDoc = new PdfDocument(stream);

    // Get the first page of the new document
    var newPage = newPageDoc.Pages[0];

    // Add the page to the existing document
    existingDoc.Pages.Add(newPage);

    // Return the modified document
    return existingDoc;
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This pattern is perfect for scenarios where you need to combine invoices, reports, or any other PDF documents stored in your database. The merged document maintains the original quality and formatting of all source PDFs. The objects are handled entirely in memory. You can also edit the pages if needed.

Handling Errors and Common Mistakes

When implementing this code, it's important to handle potential error cases. For instance, if a file cannot be read (false path) or if the byte array doesn't represent a valid PDF, the new PdfDocument() object creation might throw an exception. Always use try-catch blocks. If you are not familiar with the system, it's easy to make a mistake. Always verify the length of the array before processing.

Example: Always check if the path to the file exists before trying to read the bytes. If the byte array is null, the open operation will fail.

The ability to create, delete, or import these documents is often managed by users with appropriate passwords or security on the site. This ensures secure access to the files and prevents unauthorized write or saving operations. This topic is covered in additional topics on the IronPDF site.

Conclusion

Merging PDF byte arrays with IronPDF eliminates the complexity traditionally associated with PDF manipulation in C#. Whether you're working with documents from a database, API responses, or in-memory processing, IronPDF's straightforward API makes merging PDFs as simple as calling a single method. We hope this approach helps you achieve your goals. The end result is a clean, combined PDF. Thanks for reading, and please reply if you have further questions.

Get started with a free trial to experience how IronPDF can streamline your PDF processing workflows, or explore our licensing options for production use.

NuGet Install with NuGet

PM >  Install-Package IronPdf

Check out IronPDF on NuGet for quick installation. With over 10 million downloads, it’s transforming PDF development with C#. You can also download the DLL or Windows installer.

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