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.example.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 document = new Document();
        try {
            PdfWriter.getInstance(document,
                    new FileOutputStream("ImageRotation.pdf"));
            document.open();

            //
            // Rotate image in radian using the setRotation method.
            //
            String filename = "other-sample/src/main/resources/java.gif";
            Image image = Image.getInstance(filename);
            image.setRotation(90f);
            document.add(image);

            //
            // Rotate image in degree using the setRotationDegree method
            //
            String url = "http://localhost/xampp/img/xampp-logo-new.gif";
            image = Image.getInstance(url);
            image.setRotationDegrees(90);
            document.add(image);
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }
}
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

1 Comments

Leave a Reply