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

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

Leave a Reply