简体   繁体   中英

How to add two images in one cell in iText?

I'm currently creating a system that generates a PDF. However, I cannot put two - three images in a single cell. I tried for-looping it but it has borders. What should i do?

Please take a look at the ImagesInCell 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:

在此处输入图片说明

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:

在此处输入图片说明

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM