2015-11-09 38 views
2

我目前正在创建一个生成PDF的系统。但是,我不能在一个单元中放置两三张图像。我尝试循环它,但它有边界。我该怎么办?如何在iText中的一个单元格中添加两个图像?

+0

你所要求的是很容易实现的。你想要图像水平相邻显示吗?你想垂直组织它们吗?请详细说明您的尝试。很难相信你无法满足向单元添加多个图像的要求。另外:为什么你提到“循环”和“边界”?这两个概念在你的问题的背景下似乎不相关。如果它们与你有关,你应该解释原因。 –

回答

1

请看看ImagesInCell的例子。它使用三个图像:

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

这些是图像实例:

Image img1 = Image.getInstance(IMG1); 
Image img2 = Image.getInstance(IMG2); 
Image img3 = Image.getInstance(IMG3); 

到多个图像添加到单个细胞的最简单的方法是通过使用addElement多次:

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

结果如下所示:

enter image description here

正如您所看到的,图像自动缩放以适应单元格的宽度。如果这不是你想要的,你必须改善你的问题,因为你只声称你不能将三张图像添加到同一个单元格,而这个简单的例子证明了完全相反。

也许你想要的东西,看起来像这样:

enter image description here

在第一行与图片,我们像以前一样使用相同的addElement()方法,但我们改变图像的宽度百分比至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); 

在第二行有图像,我们使用了不同的方法:我们的包裹内的图像对象Chunk,这样我们就可以把它们彼此相邻:

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

观察到我缩放了第一个图像。如果该图像保持其原始尺寸,则三张图像不会彼此相邻。

结束语一个Chunk内的图像的优点是,我们可以混合的图像和文字:

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); 
相关问题