【问题标题】:How to add text on top of an image inside a cell?如何在单元格内的图像顶部添加文本?
【发布时间】:2014-11-28 12:49:36
【问题描述】:

我在单元格内的图像顶部(而不是下方)放置文本时遇到问题。

我的代码如下所示:

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

但文字显示在图像下方而不是在图像上方。

我能做什么?有没有办法设置从图像边框到文本内容的填充?

【问题讨论】:

  • 尝试评论img.SetAbsolutePosition()
  • 我做了,什么也没发生 :(
  • 也许你必须使用DirectContentUnder?见here

标签: c# itextsharp cell


【解决方案1】:

有不止一种方法可以实现你想要的,取决于实际的需求。

方法一:

WatermarkedImages1 示例中解释了第一种方法。在这个例子中,我们创建了一个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

WatermarkedImages2 示例中解释了第二种方法。在这种情况下,我们将每个图像添加到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:

除了将文本添加到包含图像的单元格的单元格事件的TEXTCANVAS 之外,您还可以将图像添加到包含文本的单元格的单元格事件的BACKGROUNDCANVAS

请注意:您的问题可能会作为How to add text to an image?的副本被关闭

【讨论】:

    猜你喜欢
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多