How do I add Image to a Table in iText 8?

In this example you’ll see how to add Image to a Table when creating a PDF document using iText 8. We start by finding the image resource using getResource() method and pass the absolute path to the resource name. The getResource() method return a java.net.URL object.

With this URL object in hand we then create the ImageData object using the ImageDataFactory.create() method. To the create() factory method we pass the URL object as a parameter. Finally, we create the Image object by calling the constructor of this class and passes the ImageData object as a parameter.

Here is the complete code snippet. Below we create a Premier League Ladder table showing club current position from position 1 to 10.

package org.kodejava.itext;

import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.colors.DeviceGray;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.borders.Border;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.UnitValue;
import com.itextpdf.layout.properties.VerticalAlignment;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.itextpdf.kernel.colors.DeviceGray.makeLighter;

public class TableExample {
    public static void main(String[] args) throws Exception {
        TableExample demo = new TableExample();
        demo.createTable();
    }

    private void createTable() throws Exception {
        String destination = "premier-league-ladder.pdf";
        PdfWriter writer = new PdfWriter(destination);
        PdfDocument pdf = new PdfDocument(writer);

        String[] headers = {"Position", "Club", "Played", "Won", "Drown", "Lost", "GF", "GA", "GD", "Points"};

        try (Document document = new Document(pdf)) {
            Table table = new Table(headers.length + 1);
            // Set table width to span the entire page
            table.setWidth(UnitValue.createPercentValue(100));

            URL plLogoFile = TableExample.class.getResource("/epl/pl-main-logo.png");
            ImageData plImageData = ImageDataFactory.create(Objects.requireNonNull(plLogoFile));

            table.addHeaderCell(new Cell().setBorder(Border.NO_BORDER)
                    .add(new Image(plImageData).scaleToFit(50, 50)));
            table.addHeaderCell(new Cell(1, 11).setBorder(Border.NO_BORDER)
                    .setVerticalAlignment(VerticalAlignment.MIDDLE)
                    .add(new Paragraph("Premier League Ladder").setFontSize(16).setBold()));

            for (String header : headers) {
                if (header.equals("Club")) {
                    table.addHeaderCell(new Cell(1, 2)
                            .setBackgroundColor(makeLighter(DeviceGray.GRAY))
                            .setBorderLeft(Border.NO_BORDER).setBorderRight(Border.NO_BORDER)
                            .setWidth(UnitValue.createPercentValue(28))
                            .add(new Paragraph(header)));
                } else {
                    table.addHeaderCell(newCell()
                            .setBackgroundColor(makeLighter(DeviceGray.GRAY))
                            .setWidth(UnitValue.createPercentValue(8))
                            .add(new Paragraph(header).setTextAlignment(TextAlignment.CENTER)));
                }
            }

            int position = 1;
            for (Club club : getTableData()) {
                String fileName = club.name().replace(' ', '_').toLowerCase() + ".png";
                URL logoFile = TableExample.class.getResource("/epl/logo/" + fileName);
                ImageData imageData = ImageDataFactory.create(Objects.requireNonNull(logoFile));

                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(position++))));
                table.addCell(newCell().setWidth(UnitValue.createPercentValue(1))
                        .setVerticalAlignment(VerticalAlignment.MIDDLE)
                        .add(new Image(imageData).scaleAbsolute(16, 16)));
                table.addCell(newCell().setWidth(UnitValue.createPercentValue(27))
                        .add(new Paragraph(club.name())));
                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(club.played()))));
                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(club.won()))));
                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(club.drawn()))));
                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(club.lost()))));
                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(club.goalsFor()))));
                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(club.goalsAgainst()))));
                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(club.goalDifference()))));
                table.addCell(newCell().add(newCenteredParagraph(String.valueOf(club.points()))));
            }

            document.add(table);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Cell newCell() {
        return new Cell().setBorderLeft(Border.NO_BORDER).setBorderRight(Border.NO_BORDER);
    }

    private Paragraph newCenteredParagraph(String text) {
        return new Paragraph(text).setTextAlignment(TextAlignment.CENTER);
    }

    private List<Club> getTableData() {
        List<Club> clubs = new ArrayList<>();
        clubs.add(new Club("Arsenal", 20, 4, 4, 70, 24));
        clubs.add(new Club("Liverpool", 19, 6, 2, 64, 25));
        clubs.add(new Club("Man City", 19, 5, 3, 62, 27));
        clubs.add(new Club("Aston Villa", 17, 4, 6, 59, 37));
        clubs.add(new Club("Tottenham", 15, 5, 6, 55, 39));
        clubs.add(new Club("Man United", 15, 2, 11, 39, 39));
        clubs.add(new Club("West Ham", 12, 6, 9, 43, 47));
        clubs.add(new Club("Wolves", 12, 5, 11, 42, 44));
        clubs.add(new Club("Newcastle", 12, 4, 11, 57, 45));
        clubs.add(new Club("Brighton", 10, 9, 8, 49, 44));
        return clubs;
    }

    record Club(String name, int won, int drawn, int lost, int goalsFor, int goalsAgainst) {
        public int played() {
            return won + drawn + lost;
        }

        public int goalDifference() {
            return goalsFor - goalsAgainst;
        }

        public int points() {
            return (won * 3) + drawn;
        }
    }
}

And here is the output of the generated PDF table:

Premier League Ladder Table

In the example above you can also see how to expand the width of the table to take the full width of the page.

table.setWidth(UnitValue.createPercentValue(100));

To span a table Cell to take multiple columns you can create a Cell object and specify the rowspan and colspan parameter.

table.addHeaderCell(new Cell(1, 2));

To remove the vertical border of the Cell you can set the left and right border by calling the setBorderLeft() and setBorderRight() method and passes Border.NO_BORDER as parameter.

new Cell().setBorderLeft(Border.NO_BORDER).setBorderRight(Border.NO_BORDER);

The data of the table is encapsulated using a record, this feature is introduced in Java 14, prior to this version you will create a simple POJO, which is a Java object with properties and related getters and setters method.

public record Club(String name, int won, int drawn, int lost, int goalsFor, int goalsAgainst) {}

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-core</artifactId>
    <version>8.0.3</version>
    <type>pom</type>
</dependency>

Maven Central

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 a PDF document in iText?

The following example demonstrates how to add an image into a PDF document using the iText library. An image is created using the com.itextpdf.text.Image class. To create an instance of image, we can use the Image.getInstance() method. In the example below, we create an image from an image file name a URL that points 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