DEV Community

CodeSharing
CodeSharing

Posted on • Updated on

Rotate a PDF page using Java

When viewing a PDF document, if you find the page orientation is wrong, then you'll need to adjust the page to the right orientation for better viewing. Today, this article will introduce how to rotate a PDF page with Free Spire.PDF for Java.

Import jar dependency (2 Methods)
● Download the Free Spire.PDF for Java and unzip it.Then add the Spire.Pdf.jar file to your project as dependency.

● You can also 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>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
        </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf.free</artifactId>
        <version>3.9.0</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Below is the screenshot of the input.pdf file:
Alt Text

Java Code

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.PdfPageRotateAngle;

import java.io.IOException;

public class RotatePDFPage {
    public static void main(String[] args) throws IOException {
        //Load the PDF document
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("input.pdf");

        //Get the first page
        PdfPageBase page = pdf.getPages().get(0);

        //Get the original rotation angle of the page
        int rotateAngle = page.getRotation().getValue();

        //Rotate the PDF page 90 degrees clockwise based on the original rotation angle
        rotateAngle += PdfPageRotateAngle.Rotate_Angle_90.getValue();
        page.setRotation((PdfPageRotateAngle.fromValue(rotateAngle)));

        //Save the PDF document
        pdf.saveToFile("Rotated.pdf");
    }
}
Enter fullscreen mode Exit fullscreen mode

The screenshot of the generated pdf file:
Alt Text

Top comments (0)