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 change page order in a PDF document using Free Spire.PDF for Java.
Import JAR Dependency
● You can download the free API and unzip it. Then add the Spire.Pdf.jar file to your project as dependency.
● Or you can directly add the jar dependency to maven project by adding the following configurations to the pom.xml.
<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.free</artifactId>
<version>4.3.0</version>
</dependency>
</dependencies>
Sample Code
The PdfDocument.getPages().reArrange() method offered by Free 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.
import com.spire.pdf.PdfDocument;
public class RearrangePages {
public static void main(String[] args) {
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Load the sample PDF file
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Food.pdf");
//Rearrange pages by setting a new page order
doc.getPages().reArrange(new int[]{0, 2, 1, 3});
//Save to file
doc.saveToFile("ChangeOrder.pdf");
doc.close();
}
}