Skip to main content
Skip table of contents

How to add two images in one cell?

I'm currently creating a system that generates a PDF. However, I can't put two or three images in a single cell. What should i do?

Posted on StackOverflow on Nov 9, 2015 by user5290675

Please take a look at the MultipleImagesInCell example. It uses three images:

public static final String IMG1 = "resources/images/brasil.png";
public static final String IMG2 = "resources/images/dog.bmp";
public static final String IMG3 = "resources/images/fox.bmp";

These are the image instances:

Image img1 = new Image(ImageDataFactory.create(IMG1));
Image img2 = new Image(ImageDataFactory.create(IMG2));
Image img3 = new Image(ImageDataFactory.create(IMG3));

The easiest way to add multiple images to a single cell is by using add multiple times:

Table table = new Table(1);
table.setWidthPercent(50);
table.addCell("Different images, one after the other vertically:");
Cell cell = new Cell();
// There's no image autoscaling by default in iText7
cell.add(img1.setAutoScale(true));
cell.add(img2.setAutoScale(true));
cell.add(img3.setAutoScale(true));
table.addCell(cell);
doc.add(table);

The result looks like this:

Images added to a cell

Images added to a cell

As you can see, the images were scaled by using setAutoScale(true), to fit the width of the cell. If that isn't what you want, you have to improve your question, because you only claim that you can't add three images to the same cell, whereas this simple example proves the exact opposite.

Maybe you want something that looks like this:

Images added to a cell

Images added to a cell

In the first row with images, we use the same add() method as before, but we change the width percentage of the image to 20%:

cell = new Cell();
img1.setWidthPercent(20);
cell.add(img1);
img2.setWidthPercent(20);
cell.add(img2);
img3.setWidthPercent(20);
cell.add(img3);
table.addCell(cell);

In the second row with images, we use a different approach: we have wrapped the images inside Paragraph object, so that we can put them next to each other:

Paragraph p = new Paragraph();
img1.scale(0.3f, 0.3f);
p.add(img1);
p.add(img2);
p.add(img3);
table.addCell(p);

Observe that I scaled the first image. The three images wouldn't fit next to each other if that image kept its original size.

Wrapping an image inside a Paragraph has the advantage that we can mix images and text:

p = new Paragraph("The quick brown ");
p.add(img3);
p.add(" jumps over the lazy ");
p.add(img2);
cell = new Cell();
cell.add(p);
table.addCell(cell);

Click How to add two images in one cell? if you want to see how to answer this question in iText 5.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.