How to show an image at a text field position?
This is the code I tried to replace the text field with an image image:
I find the text field by its field name:
String position = null; ListFieldPosition> fieldPositons = form.getFieldPositions("50106"); for (FieldPosition position :fieldPositons) { this.position = position.position; }
Image image = Image.getInstance("ImageFileName"); Float dimensions = position.split("x"); image.setAbsolutePosition(dimensions[0], dimensions[1]); content.addImage(image);
Posted on StackOverflow on Nov 8, 2015 by Naveenkumar Chinnakalappa
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.
In iText 7 we get an acrofield, that we are interested in, using this code:
PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);
Map fields = form.getFormFields();
PdfFormField field = fields.get("50106");
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:
PdfArray position = field.getWidgets().get(0).getRectangle();
float width = (float) (position.getAsNumber(2).getValue() - position.getAsNumber(0).getValue());
float height = (float) (position.getAsNumber(3).getValue() - position.getAsNumber(1).getValue());
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 position
value will consist of the lower-left and upper-right x and y coordinates: [llx, lly, urx, ury]
.
If you want to know some information about the page, try this:
PdfPage page = form.getField(name).getWidgets().get(0).getPage();
You can set the width and height and then position the image like this:
Image image = new Image(ImageDataFactory.create(imgSrc));
image.setHeight(height);
image.setFixedPosition((float) position.getAsNumber(0).getValue(), (float) position.getAsNumber(1).getValue());
Important:
-
If you add the image as described above, you need to remove the field (this happens automatically if you flatten the form), so you can chose between
removeField()
orflattenFields()
methods. -
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 the icon of a push button field? 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).
Click How to show an image at a text field position? if you want to see how to answer this question in iText 5.