DEV Community

Gia
Gia

Posted on • Edited on

How to Rotate PDF Pages in Java

Rotating PDF pages is a useful method for adjusting page orientation within a PDF document, allowing users to rotate pages by 90, 180, or 270 degrees clockwise or counterclockwise without altering the layout of text and images. This feature is particularly beneficial for documents that need to adapt to screen or printer orientation or change reading direction. In the following sections, I will provide a guide on how to programmatically rotate PDF pages using Java as an example.

Step 1: Install a PDF Library

I highly recommend Free Spire.PDF for Java, which is a totally standalone PDF Library. It supports a wide range of features such as creating, editing and converting of PDF files effortlessly within Java applications.

You can download it from this link to local and unzip it.

Step 2: Import JAR file to your project

Take IntelliJ IDEA 2018 as an example

  • Create a new project in IntelliJ IDEA.
  • Click “File”- “Project Structure”- “Modules”- “Dependencies” in turn.
  • Choose the “JARs or Directories” under the right green plus.
  • Find the “Spire.Pdf.jar” in the lib folder of the decompressed package and import it to the project.

Step 3: Write code

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

public class RotatePdfPage {
    public static void main(String []args){

        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();

        //Load a PDF document
        pdf.loadFromFile("sample.pdf");

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

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

        //Rotate the page 180 degrees clockwise based on the original rotation angle
        rotation += PdfPageRotateAngle.Rotate_Angle_180.getValue();
        page.setRotation(PdfPageRotateAngle.fromValue(rotation));

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

In this code, you need to create an instance of PdfDocument first and load a sample file using loadFromFile() method. Then, you can get the original rotation angle of the page using getRotation().getValue() method and rotate the page 180 degrees clockwise based on the original rotation angle. Finally, save the result file with saveToFile() method.
If you want to rotate the whole PDF file, please loop through all pages before getting the original rotation angle of the page.

Image description

Referring to the above method, you can also use this PDF component to convert PDF to Word, or print PDF files.

Top comments (0)