你的问题听起来不对。就好像您想在文档中添加图像水印,这在许多其他问题中得到了充分解释,例如在 PDF iText ASP C# 中为我的所有页面设置修复背景图像以及如何将图像添加到我的所有页面PDF?(这些答案都是关于C#的问题,但是官网有很多水印和页面事件的例子。)
就像madhesh一样,即使在您阅读了我对如何向图像添加文本的问题的回答之后,您也会使 StackOverflow 读者感到困惑。我在哪里写道:
这是一个很好的例子,这个问题的措辞没有人能正确回答。经过大量的来回评论,终于清楚OP想要在图像中添加文本水印。糟糕的短语问题可能非常令人沮丧。请在提问时考虑到这一点。在这种情况下,在弄清楚实际问的是什么之前,我给出了几个错误的答案。
您想在PdfPTable
an中添加 a,但Image
您的知识不足以理解和调整随问题答案提供的示例,例如如何将文本添加到图像?并使用 ItextSharp 在 PDF 中的图像上画线。
不过,您要问的内容非常简单。
您提到的getWatermarkedImage()
方法如下所示:
public Image getWatermarkedImage(PdfContentByte cb, Image img) 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);
template.saveState();
template.setColorStroke(BaseColor.GREEN);
template.setLineWidth(3);
template.moveTo(width * .25f, height * .25f);
template.lineTo(width * .75f, height * .75f);
template.moveTo(width * .25f, height * .75f);
template.lineTo(width * .25f, height * .25f);
template.stroke();
template.setColorStroke(BaseColor.WHITE);
template.ellipse(0, 0, width, height);
template.stroke();
template.restoreState();
return Image.getInstance(template);
}
这是从问题如何在图像上画线?
你不想画线,所以你可以删除所有画线的代码:
public Image getWatermarkedImage(PdfContentByte cb, Image img) 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);
// removed the code that draws lines
return Image.getInstance(template);
}
你想画一个而不是线条,PdfPTable
所以我们在它说的地方添加一些代码// removed the code that draws lines
。如文档所述,使用以下方法在绝对位置添加表格writeSelectedRows()
:
public Image getWatermarkedImage(PdfContentByte cb, Image img) 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);
PdfPTable table = new PdfPTable(2);
table.setTotalWidth(width);
table.getDefaultCell().setBorderColor(BaseColor.Yellow);
table.addCell("Test1");
table.addCell("Test2");
table.addCell("Test3");
table.addCell("Test4");
table.writeSelectedRows(0, -1, 0, height, template);
return Image.getInstance(template);
}
我改编了官方文档中的众多示例之一(请参阅WatermarkedImages5),结果如下:

文档中提供了实现此目的所需的所有功能。请在发布另一个问题之前阅读该文档。