Showing image on a acro text field position

时光怂恿深爱的人放手 提交于 2019-12-08 18:46:30
Bruno Lowagie

It is never a good idea to change the dimensions of an AcroField as all the content in a PDF is added at absolute positions. When you change the dimension of a field, you risk that it will overlap with other content.

Hence, your best option is to adapt the size of the image to the size of the AcroField. As you already indicated, you can get the field position like this:

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

Note that it's not a good idea to make this a string. You can use the FieldPosition object like this:

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

You can scale and position the image like this:

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

The ScaleToFit() method will scale the image in such a way that it will fit the dimensions of the form field, respecting the original aspect ratio of the image (you don't want to add a stretched image).

You need to page variable to add the image to the correct page:

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

Important:

  • If you add the image as described above, you need to remove the field (this happens automatically if you flatten the form).
  • If the form field is a button, then you shouldn't use the above code. Instead you should replace the icon of the button. This is described in my answer to the question How to change a Button Icon of a PDF Formular with itextsharp? This answer explains the standard way to do what you're trying to do, but it requires that the field where you want to add the image is a button field (and based on your question, it seems that it's a text field).
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!