How do I rotate image in iText PDF document?

You can rotate images in the iText pdf document using the setRotation(final float r) or the setRotationDegrees(final float deg) methods of the com.itextpdf.text.Image class. This method sets the rotation in radian and in degree respectively. Let’s see an example below:

package org.kodejava.itextpdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileOutputStream;
import java.io.IOException;

public class ImageRotateDemo {
    public static void main(String[] args) {
        Document doc = new Document();
        try {
            PdfWriter.getInstance(doc, new FileOutputStream("ImageRotation.pdf"));
            doc.open();

            // Rotate image in radian using the setRotation method.
            String filename = "kodejava-itextpdf/src/main/resources/java.png";
            Image image = Image.getInstance(filename);
            image.setRotation(90f);
            doc.add(image);

            // The following line to prevent the "Server returned
            // HTTP response code: 403" error.
            System.setProperty("http.agent", "Chrome");

            // Rotate image in degree using the setRotationDegree method
            String url = "https://kodejava.org/wp-content/uploads/2017/01/kodejava.png";
            image = Image.getInstance(url);
            image.setRotationDegrees(90);
            doc.add(image);
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        } finally {
            doc.close();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.3</version>
</dependency>

Maven Central

Wayan

2 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.