I have an existing PDF that I want to open up and add content to the page where a specific PDField
(or specifically PDTerminalField
, not that I think it matters) is on.
It may be on the first page or any later one.
I know the name of the field and with that, I can look it up and could even get the dimensions and the position of it on that page ( DRectangle mediabox = new PDRectangle((COSArray) fieldDict.getDictionaryObject(COSName.RECT));
)
However I can't find a way to get the number/index of the page it is on, so I can write on the correct page.
PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm();
PDField docField = acroForm.getField("the_coolest_field");
int page = docField.??? // This is the missing part.
PDPageContentStream contentStream = new PDPageContentStream(pdfDocument,
pdfDocument.getPage(page), PDPageContentStream.AppendMode.APPEND, true);
// now write something on the page where the field is in.
Using the hints given in this comment I could create a map containing the field names and the (last) page it occurred on.
Now looking up the page is as simple as
Note that this may throw a NullPointerException if that widget does not exist for some reason.
Previous answer below. It seems I was wrong about that approach, but I keep it for reference: