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

How do I scale an image in PDF document using iText?

The com.itextpdf.text.Image class represent an image of a graphic element such as JPEG, PNG or GIF that can be inserted into a PDF document. There are some methods of the com.itextpdf.text.Image class that can be used to scale the image. These methods include the following: scaleAbsolute(), scaleAbsoluteHeight(), scaleAbsoluteWidth(), scalePercent() and scaleToFit().

These are signatures of those APIs:

  • scaleAbsolute(float newWidth, fload newHeight) – Scales the image to an absolute width and an absolute height.
  • scaleAbsoluteHeight(float newHeight) – Scales the image to an absolute height.
  • scaleAbsoluteWidht(float newWidth) – Scales the image to an absolute width.
  • scalePercent(float percent) – Scales the image to a certain percentage.
  • scalePercent(float percentX, float percentY) – Scales the image to a certain percentage of width and height.
  • scaleToFit(float fitWidth, float fitHeight) – Scales the image to fit a certain width and height.

Here is a code snippet that shows how to use the scaleAbsolute(), scalePercent() and scaleToFit() methods.

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 ImageScalingDemo {
    public static void main(String[] args) {
        Document doc = new Document();
        try {
            PdfWriter.getInstance(doc, new FileOutputStream("ImageScaling.pdf"));
            doc.open();

            // Scale the image to an absolute width and an absolute
            // height
            String filename = "kodejava-itextpdf/src/main/resources/java.png";
            Image image = Image.getInstance(filename);
            image.scaleAbsolute(200f, 200f);
            doc.add(image);

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

            // Scale the image to a certain percentage
            String url = "https://kodejava.org/wp-content/uploads/2017/01/kodejava.png";
            image = Image.getInstance(url);
            image.scalePercent(200f);
            doc.add(image);

            // Scales the image so that it fits a certain width and
            // height
            image = Image.getInstance(url);
            image.scaleToFit(100f, 200f);
            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

How do I set the absolute position of an image in iText?

To set the absolute position of an image you can use the setAbsolutePosition() method. This method takes two parameters the X and Y coordinate where the image will be placed. In the pdf document the 0, 0 coordinate is located at the left bottom corner of the document. 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 ImageAbsolutePosition {
    public static void main(String[] args) {
        Document doc = new Document();
        try {
            PdfWriter.getInstance(doc, new FileOutputStream("ImageAbsolutePosition.pdf"));
            doc.open();

            // Sets the absolute position of the image.
            String filename = "kodejava-itextpdf/src/main/resources/java.png";
            Image image = Image.getInstance(filename);
            image.setAbsolutePosition(0f, 0f);
            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

How do I add an image into PDF document in iText?

The following example demonstrate how to add an image into a PDF document using the iText library. Image is created using the com.itextpdf.text.Image class. To create an instance of image we can use the Image.getInstance() method. Below we create an image from an image file name a URL that point to an image resource.

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 ImageDemo {
    public static void main(String[] args) {
        Document doc = new Document();
        try {
            PdfWriter.getInstance(doc, new FileOutputStream("ImageDemo.pdf"));
            doc.open();

            // Creating image by file name
            String filename = "kodejava-itextpdf/src/main/resources/java.png";
            Image image = Image.getInstance(filename);
            doc.add(image);

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

            // Creating image from a URL
            String url = "https://kodejava.org/wp-content/uploads/2017/01/kodejava.png";
            image = Image.getInstance(url);
            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

How do I set an image as the content of a cell in iText?

This example demonstrate how to add an image into a cell in iText. One way to set image into cell’s content is by creating an instance of com.itextpdf.text.pdf.PdfPCell and pass an image object (com.itextpdf.text.Image) in the constructor parameter. The constructor also accept a boolean value whether the image will be fitted into the cell or not.

package org.kodejava.itextpdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Objects;

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

            // Creates a table
            PdfPTable table = new PdfPTable(3);
            PdfPCell cell1 = new PdfPCell(new Phrase("Cell 1"));

            // Creates an image and set it as cell's content
            URL resource = TableImageDemo.class.getResource("/java.png");
            Image image = Image.getInstance(Objects.requireNonNull(resource));
            PdfPCell cell2 = new PdfPCell(image, false);
            cell2.setPadding(10);

            PdfPCell cell3 = new PdfPCell(new Phrase("Cell 3"));

            // Add cells to table
            table.addCell(cell1);
            table.addCell(cell2);
            table.addCell(cell3);

            doc.add(table);
        } 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

How do I get and display an image in Applet?

To display an image in an applet we first need to obtain the image object itself. A call to applet’s getImage(URL url, String name) method help us to create an image object from the specified URL of the image.

For displaying the image on the applet’s screen we draw it in the paint() method using Graphics.drawImage() method.

package org.kodejava.applet;

import java.applet.Applet;
import java.awt.*;

public class AppletGetImage extends Applet {
    private Image logo;

    @Override
    public void init() {
        // Get an Image object that can be painted on the Applet
        // screen. We need to supply the URL of the document as
        // the base location of the image and the location of the
        // image relative the base URL. 
        logo = getImage(getDocumentBase(), "/images/logo.png");
    }

    @Override
    public void paint(Graphics g) {
        g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
        g.drawImage(logo, 10, 10, this);
    }
}

How do I change JFrame image icon?

This code snippet demonstrates how to change a JFrame image icon using the setIconImage() method.

package org.kodejava.swing;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

public class FrameIconExample extends JFrame {
    public static void main(String[] args) {
        FrameIconExample frame = new FrameIconExample();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        // Set the window size and its title
        frame.setSize(new Dimension(500, 500));
        frame.setTitle("Frame Icon Example");

        // Read the image that will be used as the application icon.
        // Using "/" in front of the image file name will locate the
        // image at the root folder of our application. If you don't
        // use a "/" then the image file should be on the same folder
        // with your class file.
        try {
            URL resource = frame.getClass().getResource("/logo.png");
            BufferedImage image = ImageIO.read(resource);
            frame.setIconImage(image);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Display the form
        frame.setVisible(true);
    }
}
Change JFrame Image Icon

Change JFrame Image Icon