Skip to footer content
USING IRONPDF

How to Rearrange PDF Pages in C# Programmatically

How to Rearrange Pages in PDF C# With IronPDF: Image 1 - Rearrange Pages in PDFs C#

Rearranging pages in a PDF file using C# eliminates hours of manual work when you need to reorganize reports, reorder contract annexes, or rebuild document packages before delivery. IronPDF provides a straightforward API for loading a PDF, specifying a new page sequence, and saving the result in just a few lines of .NET code. This article walks through five practical techniques: basic page reordering, bulk reversal, moving a single page to a new index, deleting unwanted pages, and working entirely in memory without touching the file system.

IronPdf.PdfDocument.FromFile("input.pdf")
    .CopyPages(new[] { 2, 0, 1, 3 })
    .SaveAs("reordered.pdf");
IronPdf.PdfDocument.FromFile("input.pdf")
    .CopyPages(new[] { 2, 0, 1, 3 })
    .SaveAs("reordered.pdf");
$vbLabelText   $csharpLabel

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.

How Do You Get Started with IronPDF?

Add IronPDF to any .NET 8 or .NET 10 project in seconds using the NuGet Package Manager or the .NET CLI. No additional runtime dependencies or native binaries are required on Windows, Linux, or macOS.

dotnet add package IronPdf
dotnet add package IronPdf
SHELL

Once the package is installed, add using IronPdf; at the top of your C# file. A valid license key unlocks full commercial use; a free trial license is available for evaluation. Set your key before calling any API:

IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
$vbLabelText   $csharpLabel

With the package referenced and the license configured, every example in this article will run without modification. The IronPDF NuGet package targets .NET Standard 2.0 and above, so it works in .NET Framework 4.6.2+, .NET Core, and all modern .NET versions.

How Does Page Reordering Work in C#?

The process to rearrange pages in a PDF using C# involves loading the source document, specifying the desired page order through a page-index array, and saving the output file. IronPDF provides the CopyPages method to extract and reorder pages from a PDF into a new PdfDocument object.

The following code demonstrates how to reorder pages by creating a new int array that defines the target sequence. Each value in the array represents a page index from the original document, where pages use zero-based indexing (page 0 is the first page).

using IronPdf;

// Load the source document from file path
var pdf = PdfDocument.FromFile("quarterly-report.pdf");

// Define new page order: move page 3 to front, then pages 1, 2, 0
int[] pageOrder = new int[] { 3, 1, 2, 0 };

// Copy each requested page into its own PdfDocument
var pageDocs = new List<PdfDocument>();
foreach (var idx in pageOrder)
{
    // CopyPage returns a PdfDocument containing only that page
    var single = pdf.CopyPage(idx);
    pageDocs.Add(single);
}

// Merge the single-page docs into one ordered document
using var merged = PdfDocument.Merge(pageDocs.ToArray());

// Save the new ordered PDF
merged.SaveAs("report-reorganized.pdf");
using IronPdf;

// Load the source document from file path
var pdf = PdfDocument.FromFile("quarterly-report.pdf");

// Define new page order: move page 3 to front, then pages 1, 2, 0
int[] pageOrder = new int[] { 3, 1, 2, 0 };

// Copy each requested page into its own PdfDocument
var pageDocs = new List<PdfDocument>();
foreach (var idx in pageOrder)
{
    // CopyPage returns a PdfDocument containing only that page
    var single = pdf.CopyPage(idx);
    pageDocs.Add(single);
}

// Merge the single-page docs into one ordered document
using var merged = PdfDocument.Merge(pageDocs.ToArray());

// Save the new ordered PDF
merged.SaveAs("report-reorganized.pdf");
$vbLabelText   $csharpLabel

Output PDF Document

How to Rearrange Pages in PDF C# With IronPDF: Image 2 - Output for first example of how to rearrange pages in PDF C#

The CopyPages method accepts an IEnumerable<int> of page-index values that match your desired arrangement. This approach lets you rearrange PDF pages, duplicate specific pages, or extract a subset into a separate document. The method returns a new PdfDocument object, leaving the original source document unchanged. Because the original is never mutated, you can safely call CopyPages multiple times to generate different orderings from the same source file.

For teams working in Java environments, IronPDF for Java exposes similar page-manipulation methods and a compatible API surface, so skills transfer across language targets.

How Do You Understand Zero-Based Page Indexing?

IronPDF uses zero-based page indexes throughout its API. Page 0 is the first physical page, page 1 is the second, and so on. When you build your index array, count from zero rather than from one. An out-of-range index throws an ArgumentOutOfRangeException, so always validate the array values against PdfDocument.PageCount before calling CopyPages in production code.

A safe validation pattern is to check that every index in the array falls within [0, PageCount - 1] before passing the array to any page-copy method. This prevents runtime exceptions in scenarios where the input document changes shape between processing steps.

How Can Multiple Pages Be Rearranged at Once?

When a PDF document contains many pages, you can rearrange the entire structure in a single pass. The code below shows how to reverse all pages or create any custom sequence by computing the index array programmatically.

using IronPdf;

// Load PDF document with several pages
var doc = PdfDocument.FromFile("quarterly-report.pdf");
int count = doc.PageCount;

// Build reversed single-page PDFs
var pages = new List<PdfDocument>();
for (int i = count - 1; i >= 0; i--)
{
    // Copy a single page as a standalone PdfDocument
    pages.Add(doc.CopyPage(i));
}

// Merge all the reversed single-page PDFs
using var reversed = PdfDocument.Merge(pages.ToArray());

// Save to a new filename
reversed.SaveAs("report-reversed.pdf");
using IronPdf;

// Load PDF document with several pages
var doc = PdfDocument.FromFile("quarterly-report.pdf");
int count = doc.PageCount;

// Build reversed single-page PDFs
var pages = new List<PdfDocument>();
for (int i = count - 1; i >= 0; i--)
{
    // Copy a single page as a standalone PdfDocument
    pages.Add(doc.CopyPage(i));
}

// Merge all the reversed single-page PDFs
using var reversed = PdfDocument.Merge(pages.ToArray());

// Save to a new filename
reversed.SaveAs("report-reversed.pdf");
$vbLabelText   $csharpLabel

Reversed PDF Pages Output

How to Rearrange Pages in PDF C# With IronPDF: Image 3 - PDF with reversed pages so the conclusion is at the start

This code loads a PDF file, queries PageCount, and constructs a list that reverses the page sequence. The for loop builds the new order dynamically, making the approach scale to documents of any length. You can adapt the same pattern to any non-trivial ordering: alphabetical by metadata, sorted by file size if extracting individual pages from multiple sources, or shuffled for anonymized test data.

You can also swap exactly two pages without rebuilding the full list. To swap pages 0 and 2 while keeping page 1 in place on a three-page document, pass new int[] { 2, 1, 0 } as your index array. The IronPDF page manipulation documentation includes additional examples for copying, inserting, and deleting pages.

How Do You Handle Large Documents Efficiently?

For documents with hundreds of pages, calling CopyPage in a tight loop allocates many intermediate objects. A more efficient alternative is to build the full index array once and pass it directly to CopyPages. The CopyPages(IEnumerable<int>) overload performs the entire reordering in a single internal pass, which is faster and uses less memory than merging individually copied pages.

When processing large batches of PDFs, consider disposing of intermediate PdfDocument objects promptly using using statements or explicit Dispose() calls. The .NET garbage collector manages memory automatically, but eagerly releasing unmanaged resources reduces peak memory usage for high-throughput services.

How Do You Move a Single Page to a New Location?

Moving one page to a different position requires combining a copy, a removal, and an insertion. The InsertPdf method places a PdfDocument at any index within the target document.

using IronPdf;

// Load the input PDF file
var pdf = PdfDocument.FromFile("presentation.pdf");
int sourceIndex = 1;   // page to move
int targetIndex = 3;   // destination position

// Track direction to handle index shift after removal
bool movingForward = targetIndex > sourceIndex;

// 1. Copy the page to move (produces a one-page PdfDocument)
var pageDoc = pdf.CopyPage(sourceIndex);

// 2. Remove the original page from its current position
pdf.RemovePage(sourceIndex);

// 3. Adjust target index if moving forward (removal shifts remaining pages left)
if (movingForward)
    targetIndex--;

// 4. Insert the copied page at the target position
pdf.InsertPdf(pageDoc, targetIndex);

// Save the result
pdf.SaveAs("presentation-reordered.pdf");
using IronPdf;

// Load the input PDF file
var pdf = PdfDocument.FromFile("presentation.pdf");
int sourceIndex = 1;   // page to move
int targetIndex = 3;   // destination position

// Track direction to handle index shift after removal
bool movingForward = targetIndex > sourceIndex;

// 1. Copy the page to move (produces a one-page PdfDocument)
var pageDoc = pdf.CopyPage(sourceIndex);

// 2. Remove the original page from its current position
pdf.RemovePage(sourceIndex);

// 3. Adjust target index if moving forward (removal shifts remaining pages left)
if (movingForward)
    targetIndex--;

// 4. Insert the copied page at the target position
pdf.InsertPdf(pageDoc, targetIndex);

// Save the result
pdf.SaveAs("presentation-reordered.pdf");
$vbLabelText   $csharpLabel

Original PDF vs. The Output

How to Rearrange Pages in PDF C# With IronPDF: Image 4 - Comparison of the input PDF vs. the output PDF with the moved page

The algorithm copies the source page, removes it from the document (which shifts all subsequent page indexes down by one), adjusts the target index to account for that shift, and then inserts the page at the corrected position. This pattern handles both forward and backward moves correctly. Use it when you need surgical control over one or two pages without reconstructing the entire document.

For situations that call for inserting content from a second PDF rather than moving an existing page, InsertPdf accepts any PdfDocument as its first argument, including documents generated from HTML using the IronPDF HTML-to-PDF API.

How Do You Delete Pages and Reorder Using MemoryStream?

Applications that automate PDF workflows sometimes need to manipulate documents without writing intermediate files to disk. Loading from a byte array and exporting to a MemoryStream keeps all processing in memory, which is faster for transient operations and avoids file-system permissions issues in containerized or serverless environments.

using IronPdf;
using System.IO;

// Load PDF from byte array (simulating input from a database or API response)
byte[] pdfBytes = File.ReadAllBytes("report-with-blank.pdf");
var pdf = new PdfDocument(pdfBytes);

// Delete the blank page at index 2 (zero-based)
pdf.RemovePage(2);

// Reorder remaining pages: new sequence from a four-page document
var reorderedPdf = pdf.CopyPages(new int[] { 1, 0, 2, 3 });

// Export to MemoryStream for further processing (e.g., HTTP response body)
MemoryStream outputStream = reorderedPdf.Stream;

// Or save directly using the BinaryData property
File.WriteAllBytes("cleaned-report.pdf", reorderedPdf.BinaryData);
using IronPdf;
using System.IO;

// Load PDF from byte array (simulating input from a database or API response)
byte[] pdfBytes = File.ReadAllBytes("report-with-blank.pdf");
var pdf = new PdfDocument(pdfBytes);

// Delete the blank page at index 2 (zero-based)
pdf.RemovePage(2);

// Reorder remaining pages: new sequence from a four-page document
var reorderedPdf = pdf.CopyPages(new int[] { 1, 0, 2, 3 });

// Export to MemoryStream for further processing (e.g., HTTP response body)
MemoryStream outputStream = reorderedPdf.Stream;

// Or save directly using the BinaryData property
File.WriteAllBytes("cleaned-report.pdf", reorderedPdf.BinaryData);
$vbLabelText   $csharpLabel

The PdfDocument constructor accepts a byte[] directly, and the Stream property returns the resulting PDF as a MemoryStream. This pattern suits ASP.NET Core controllers that return file responses, Azure Functions that read and write to Blob Storage, and background services that process batches of PDFs from a message queue. The library handles memory management efficiently even for large documents with embedded images.

Refer to the PdfDocument API reference to explore the full set of page-operation methods, including rotation, extraction, and stamping.

How Do You Process PDF Pages in an ASP.NET Core Controller?

Returning a reordered PDF directly from a controller is straightforward. Call RemovePage or CopyPages on the loaded document, then write BinaryData to the response:

using IronPdf;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/pdf")]
public class PdfController : ControllerBase
{
    [HttpPost("reorder")]
    public IActionResult Reorder(IFormFile file, [FromQuery] string order)
    {
        // Parse comma-separated page indexes from query string
        var indexes = order.Split(',').Select(int.Parse).ToArray();

        using var stream = file.OpenReadStream();
        using var ms = new System.IO.MemoryStream();
        stream.CopyTo(ms);

        var pdf = new PdfDocument(ms.ToArray());
        var reordered = pdf.CopyPages(indexes);

        // Return the reordered PDF as a downloadable file
        return File(reordered.BinaryData, "application/pdf", "reordered.pdf");
    }
}
using IronPdf;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/pdf")]
public class PdfController : ControllerBase
{
    [HttpPost("reorder")]
    public IActionResult Reorder(IFormFile file, [FromQuery] string order)
    {
        // Parse comma-separated page indexes from query string
        var indexes = order.Split(',').Select(int.Parse).ToArray();

        using var stream = file.OpenReadStream();
        using var ms = new System.IO.MemoryStream();
        stream.CopyTo(ms);

        var pdf = new PdfDocument(ms.ToArray());
        var reordered = pdf.CopyPages(indexes);

        // Return the reordered PDF as a downloadable file
        return File(reordered.BinaryData, "application/pdf", "reordered.pdf");
    }
}
$vbLabelText   $csharpLabel

This controller reads the uploaded file, accepts a comma-separated page order via query string, and streams the reordered PDF back as a response. No temporary files are written at any point. The same approach works for generating PDFs in ASP.NET Core from HTML or templates.

How Do You Merge PDFs After Reordering?

Reordering pages often goes hand in hand with combining content from multiple source files. IronPDF's PdfDocument.Merge method accepts an array of PdfDocument objects and joins them in the supplied order, which pairs naturally with the page-copy techniques shown above.

using IronPdf;

// Load two separate PDF files
var docA = PdfDocument.FromFile("section-a.pdf");
var docB = PdfDocument.FromFile("section-b.pdf");

// Reorder pages within each source document
var reorderedA = docA.CopyPages(new int[] { 1, 0, 2 });
var reorderedB = docB.CopyPages(new int[] { 0, 2, 1 });

// Merge into a single output document
using var combined = PdfDocument.Merge(reorderedA, reorderedB);
combined.SaveAs("combined-report.pdf");
using IronPdf;

// Load two separate PDF files
var docA = PdfDocument.FromFile("section-a.pdf");
var docB = PdfDocument.FromFile("section-b.pdf");

// Reorder pages within each source document
var reorderedA = docA.CopyPages(new int[] { 1, 0, 2 });
var reorderedB = docB.CopyPages(new int[] { 0, 2, 1 });

// Merge into a single output document
using var combined = PdfDocument.Merge(reorderedA, reorderedB);
combined.SaveAs("combined-report.pdf");
$vbLabelText   $csharpLabel

After the merge, the resulting document contains all pages from reorderedA followed by all pages from reorderedB. You can chain additional Merge calls or pass more documents to combine any number of sources. The IronPDF merge and split documentation covers splitting documents into individual sections, which is the inverse operation.

For a deeper look at merging byte arrays and in-memory documents, the guide on merging PDFs from byte arrays in C# walks through database-backed workflows where documents are stored as binary blobs rather than file paths.

What Are the Best Practices for PDF Page Management?

Defensive coding habits prevent subtle bugs and production failures when manipulating PDF pages at scale. Applying these practices consistently makes page-reordering code easier to test and maintain.

Always validate page indexes against PdfDocument.PageCount before passing them to CopyPages or RemovePage. An index that falls outside [0, PageCount - 1] raises an ArgumentOutOfRangeException at runtime. A one-line guard check eliminates this category of failure entirely.

Prefer the CopyPages(IEnumerable<int>) overload over manually looping through CopyPage when working with multi-page reorderings. The batch overload processes the full sequence in a single pass, reducing both allocations and execution time. Reserve the per-page loop pattern for cases where you need to apply per-page transformations, such as rotating individual pages before merging.

Wrap intermediate PdfDocument objects in using statements to ensure their unmanaged resources are freed immediately after use. This is especially important in web request handlers and background jobs, where many documents can accumulate in memory if intermediate objects are not disposed promptly. The IronPDF troubleshooting guide covers common memory and performance patterns in detail.

When building document automation pipelines, consider separating the reordering logic from file input/output. Accept and return byte[] or MemoryStream in your service layer to keep unit tests fast and avoid file-system dependencies. The IronPDF examples for PDF page operations show patterns for both file-path and in-memory workflows side by side.

What Are Your Next Steps?

Rearranging PDF pages in C# with IronPDF reduces a complex document-manipulation task to a handful of method calls. The core techniques covered in this article include reordering pages with an index array using CopyPages, reversing all pages programmatically with a loop, moving a single page by combining CopyPage, RemovePage, and InsertPdf, deleting unwanted pages before reordering, and processing documents entirely in memory using byte arrays and MemoryStream.

Each of these patterns integrates with the rest of the IronPDF feature set. After rearranging pages, you might add a watermark or stamp, crop individual pages, or add page numbers before delivering the final document. The IronPDF how-to guides provide code examples for each of these follow-on operations.

Start with a free trial license to test page reordering and all other IronPDF features in your own environment. When you are ready to deploy, review the IronPDF licensing options to find the tier that fits your project's requirements. The IronPDF documentation and object reference are available whenever you need to explore advanced scenarios such as digital signatures, PDF/A compliance, and accessibility tagging.

Frequently Asked Questions

How do I rearrange PDF pages in C# using IronPDF?

Load the PDF with PdfDocument.FromFile, create an int[] specifying the desired zero-based page order, then call pdf.CopyPages(indexArray) and save the result with SaveAs.

What is zero-based page indexing in IronPDF?

IronPDF numbers pages starting at 0. The first page is index 0, the second is index 1, and so on. Always validate that every index in your array falls within [0, PageCount - 1] before calling CopyPages.

Can I reorder PDF pages without saving a temporary file?

Yes. Load the PDF from a byte[] using new PdfDocument(bytes), call CopyPages, then access the result via reorderedPdf.BinaryData or reorderedPdf.Stream without any file system writes.

How do I move a single page to a different position in a PDF?

Use a three-step pattern: call CopyPage(sourceIndex) to extract the page, call RemovePage(sourceIndex) to delete it from the document, then call InsertPdf(pageDoc, targetIndex) to place it at the new position. Adjust the target index by -1 when moving forward to account for the shift caused by removal.

How do I delete a page from a PDF in C#?

Call pdf.RemovePage(index) where index is the zero-based page number to remove. After removal, all subsequent page indexes shift down by one.

Can I return a reordered PDF from an ASP.NET Core controller?

Yes. Load the uploaded file into a byte[], call CopyPages with the desired index array, then return File(reordered.BinaryData, "application/pdf", "reordered.pdf") from your controller action.

How do I merge multiple reordered PDFs into one document?

Call CopyPages on each source document to produce independently reordered PdfDocument objects, then pass them all to PdfDocument.Merge(docA, docB) to produce a single combined output.

What is the most efficient way to reorder pages in a large PDF?

Use the CopyPages(IEnumerable<int>) overload with the full index array rather than calling CopyPage in a loop. The batch overload processes the entire sequence in a single internal pass, reducing allocations and execution time.

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

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me