显示在acro文本字段位置的图象

时间:2015-11-08 17:03:42

标签: itext itextpdf

我有一个PDF文档,其中包含已经分享给客户端的acro文本字段。现在,客户端希望在其中一个文本字段中插入签名图像。我的经理让我试着这样做。我的想法是替换文本字段位置顶部的图像,并将文本字段的大小调整为图像大小。

为了将pdf的acro文本字段替换为图像,我正在尝试如下

1.Finding the text field by its field id 

String position = null; 
List<FieldPosition> fieldPositons = form.getFieldPositions("50106");
                    for (FieldPosition position :fieldPositons) {
                        this.position = position.position;
                    }
2. Setting the image into that position of text field
     Image image = Image.getInstance("ImageFileName");
Float dimensions = position.split("x");
image.setAbsolutePosition(dimensions[0], dimensions[1]);    
content.addImage(image);

根据给定的图像宽度和高度,我需要更改acro文本字段的宽度和高度。

任何人都可以尝试如下,我的逻辑是否适用于itext pdf库。让我知道是否有任何想法用图像

替换acro文本字段

1 个答案:

答案 0 :(得分:0)

改变AcroField的尺寸绝不是一个好主意,因为PDF中的所有内容都是在绝对位置添加的。当您更改字段的维度时,您可能会与其他内容重叠。

因此,您最好的选择是使图像的大小适应AcroField的大小。正如您已经指出的那样,您可以获得这样的字段位置:

AcroFields.FieldPosition f = form.GetFieldPositions("50106")[0];

请注意,将其设为string不是一个好主意。您可以像这样使用FieldPosition对象:

int page = f.page;
Rectangle rect = f.position;

您可以像这样缩放和定位图像:

Image image = Image.getInstance("ImageFileName");
image.ScaleToFit(rect.Width, rect.Height);
image.SetAbsolutePosition(rect.Left, rect.Bottom);

ScaleToFit()方法将缩放图像,使其适合表单字段的尺寸,尊重图像的原始宽高比(您不希望添加拉伸图片)。

您需要page变量才能将图像添加到正确的页面:

PdfContentByte canvas = stamper.GetOverContent(page);
canvas.AddImage(image);

重要:

  • 如果您按上述方式添加图片,则需要删除该字段(如果展平表单,则会自动执行此操作。)
  • 如果表单字段是按钮,则不应使用上面的代码。相反,您应该替换按钮的图标。这在我对问题How to change a Button Icon of a PDF Formular with itextsharp?的回答中有所描述。这个答案解释了你想要做的事情的标准方法,但它要求你想要添加图像的字段是一个按钮字段(并且基于在你的问题上,它似乎是一个文本字段)。