Java: Rearrange Pages in PDF

When you receive a PDF file with pages out of order, you may need to change the page order for a better viewing experience. In this article, you will learn how to programmatically rearrange pages in a PDF file using Spire.PDF for Java.

Install Spire.PDF for Java

First of all, you're required to add the Spire.PDF.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>10.3.4</version>
    </dependency>
</dependencies>
    

Rearrange Pages in PDF

The PdfDocument.getPages().reArrange() method offered by Spire.PDF for Java allows you to change the PDF page order quickly and effortlessly. The detailed steps are as follows.

  • Create a PdfDocument object.
  • Load a sample PDF file using PdfDocument.loadFromFile() method.
  • Rearrange the pages using PdfDocument.getPages().reArrange() method.
  • Save the document to another file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;

public class RearrangePages {

    public static void main(String[] args) {

        //Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        //Load a sample PDF file
        doc.loadFromFile("input.pdf");

        //Rearrange pages by setting a new page order
        doc.getPages().reArrange(new int[]{0, 2, 1, 3});

        //Save the document to another file
        doc.saveToFile("ChangeOrder.pdf");
        doc.close();
    }
}

Java: Rearrange Pages in PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.