C# 如何在单元格内的图像顶部添加文本?
我无法将文本放置在单元格内图像的顶部(而不是下方) 我的代码如下所示:C# 如何在单元格内的图像顶部添加文本?,c#,itextsharp,cell,C#,Itextsharp,Cell,我无法将文本放置在单元格内图像的顶部(而不是下方) 我的代码如下所示: Image img = Image.GetInstance(imagePatch); img.Alignment = Image.UNDERLYING; img.ScaleToFit(img.Width, img.Height); img.ScaleAbsoluteWidth(ptable.TotalWidth); pcell.AddElement(img); pcell.addElement(new Paragraph("
Image img = Image.GetInstance(imagePatch);
img.Alignment = Image.UNDERLYING;
img.ScaleToFit(img.Width, img.Height);
img.ScaleAbsoluteWidth(ptable.TotalWidth);
pcell.AddElement(img);
pcell.addElement(new Paragraph("text", font));
img.SetAbsolutePosition(0, ptable.TotalHeight);`
但是文本显示在图像下方而不是上方
我能做什么?有没有办法将填充从图像边框设置为文本内容?根据实际需要,有多种方法可以实现您想要的效果 方法1: 示例中解释了第一种方法。在本例中,我们创建了一个
PdfTemplate
,在其中添加了一个图像以及写在该图像顶部的一些文本。然后,我们可以将此PdfTemplate
包装在图像中,并将该图像及其水印添加到单元格中
这是执行所有魔术的方法:
public Image getWatermarkedImage(PdfContentByte cb, Image img, String watermark) throws DocumentException {
float width = img.getScaledWidth();
float height = img.getScaledHeight();
PdfTemplate template = cb.createTemplate(width, height);
template.addImage(img, width, 0, 0, height, 0, 0);
ColumnText.showTextAligned(template, Element.ALIGN_CENTER,
new Phrase(watermark, FONT), width / 2, height / 2, 30);
return Image.getInstance(template);
}
方法2.a
第二种方法在示例中进行了说明。在本例中,我们将每个图像添加到PdfPCell
。此PdfPCell
将缩放图像,使其适合页面宽度。要添加水印,我们使用单元格事件:
class WatermarkedCell implements PdfPCellEvent {
String watermark;
public WatermarkedCell(String watermark) {
this.watermark = watermark;
}
public void cellLayout(PdfPCell cell, Rectangle position,
PdfContentByte[] canvases) {
PdfContentByte canvas = canvases[PdfPTable.TEXTCANVAS];
ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER,
new Phrase(watermark, FONT),
(position.getLeft() + position.getRight()) / 2,
(position.getBottom() + position.getTop()) / 2, 30);
}
}
此单元格事件的使用方式如下:
PdfPCell cell;
cell = new PdfPCell(Image.getInstance(IMAGE1), true);
cell.setCellEvent(new WatermarkedCell("Bruno"));
table.addCell(cell);
cell = new PdfPCell(Image.getInstance(IMAGE2), true);
cell.setCellEvent(new WatermarkedCell("Dog"));
table.addCell(cell);
cell = new PdfPCell(Image.getInstance(IMAGE3), true);
cell.setCellEvent(new WatermarkedCell("Fox"));
table.addCell(cell);
cell = new PdfPCell(Image.getInstance(IMAGE4), true);
cell.setCellEvent(new WatermarkedCell("Bruno and Ingeborg"));
table.addCell(cell);
如果所有图像的大小大致相同,并且您不想担心图像是否适合页面,则可以使用这种方法
方法2.b:
除了将文本添加到包含图像的单元格事件的文本画布
,您还可以将图像添加到包含文本的单元格事件的背景画布
请注意:您的问题有可能会以重复的问题结束请尝试注释
img.SetAbsolutePosition()
。我做了,但什么也没发生:(可能您必须使用下的DirectContents
?请参阅。