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

Wayan

Leave a Reply

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