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 = Image.getInstance(IMG1);
Image img2 = Image.getInstance(IMG2);
Image img3 = Image.getInstance(IMG3);

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

PdfPTable table = new PdfPTable(1);
table.setWidthPercentage(50);
table.addCell("Different images, one after the other vertically:");
PdfPCell cell = new PdfPCell();
cell.addElement(img1);
cell.addElement(img2);
cell.addElement(img3);
table.addCell(cell);
document.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 automatically, 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 addElement() method as before, but we change the width percentage of the image to 20%:

cell = new PdfPCell();
img1.setWidthPercentage(20);
cell.addElement(img1);
img2.setWidthPercentage(20);
cell.addElement(img2);
img3.setWidthPercentage(20);
cell.addElement(img3);
table.addCell(cell);

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

Paragraph p = new Paragraph();
img1.scalePercent(30);
p.add(new Chunk(img1, 0, 0, true));
p.add(new Chunk(img2, 0, 0, true));
p.add(new Chunk(img3, 0, 0, true));
cell = new PdfPCell();
cell.addElement(p);
table.addCell(cell);

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 Chunk has the advantage that we can mix images and text:

p = new Paragraph("The quick brown ");
p.add(new Chunk(img3, 0, 0, true));
p.add(" jumps over the lazy ");
p.add(new Chunk(img2, 0, 0, true));
cell = new PdfPCell();
cell.addElement(p);
table.addCell(cell);
JavaScript errors detected

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

If this problem persists, please contact our support.