How to find the absolute position and dimension of a field?

Tags: formsfield propertiesfield positionInspect fieldsiText 5

Given an field name, is it possible to find the absolute position and dimension of that particular field (getLeft(), getTop(), getWidth(), getHeight())?

And is the opposite possible: if I know the position, can I get the name of the field?

Posted on StackOverflow on Apr 16, 2014 by ahairshi

First part of your question:

Suppose that you have an AcroFields instance (form), either retrieved from a PdfReader (read only) or a PdfStamper instance, then you can get the field position of the first widget that corresponds with a specific field name like this:

Rectangle rectangle = form.getFieldPositions(name).get(0).position;

Note that one field can correspond with multiple widgets. For instance, to get the second widget, you need:

Rectangle rectangle = form.getFieldPositions(name).get(1).position;

Of course: you probably also want to know the page number:

int page = form.getFieldPositions(name).get(0).page;

Second part of your question

Fields correspond with widget annotations. If you know the page number of the widget annotation, you could get the page dictionary and inspect the entries of the /Annots array. You'll have to loop over the different annotations, inspecting each annotation's /Rect entry. Once you find a match, you need to crawl the content for the field that corresponds with the annotation. That's more work than can be provided in a code sample on this site.