Swap pages

GroupDocs.Merger for Python via .NET lets you swap the positions of any two pages within a document. The result is a new document where the two specified pages have exchanged positions — all other pages remain in their original order. The swap is configured through SwapOptions.

Here are the steps to swap document pages:

  • Instantiate Merger with the path to the source document.
  • Create a SwapOptions object with the two 1-based page numbers to exchange.
  • Call merger.swap_pages() passing the SwapOptions object.
  • Call merger.save() to write the resulting document.
from groupdocs.merger import Merger
from groupdocs.merger.domain.options import SwapOptions

def swap_document_pages():
    # Load the source PDF document
    with Merger("./input.pdf") as merger:
        # Swap page 1 and page 3 — they will exchange positions in the output
        merger.swap_pages(SwapOptions(1, 3))
        # Save the document with the pages swapped
        merger.save("./output.pdf")

if __name__ == "__main__":
    swap_document_pages()

input.pdf is a sample file used in this example. Click here to download it.

Binary file (PDF, 336 KB)

Download full output

Explanation

  • Load source document: Merger("./input.pdf") opens the document as a context manager, ensuring resources are released on exit.
  • SwapOptions(1, 3): takes two 1-based page numbers. After the operation, page 1 moves to position 3 and page 3 moves to position 1.
  • merger.swap_pages(): applies the swap in memory. The original file is not modified.
  • merger.save("./output.pdf"): writes the resulting document with the pages in their new order.
Tip
To move a single page to a specific position without swapping, use Move page instead.

API reference

See also