DEV Community


Posted on

Rearrange PDF Pages Using Java

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.

Enter fullscreen mode Exit fullscreen mode

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.

  1. Create a PdfDocument object.
  2. Load a sample PDF file using PdfDocument.loadFromFile() method.
  3. Rearrange the pages using PdfDocument.getPages().reArrange() method.
  4. 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

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

        //Save to file
Enter fullscreen mode Exit fullscreen mode


Discussion (0)