I am developing a program with C# and the library PDFSharp. I am currently using the following code to get the X and Y coordinates of a specific AcroField in a PDF document:
PdfTextField imageField = (PdfTextField)inForm.Fields[elementName];
PdfRectangle rect = imageField.Elements.GetRectangle(PdfAnnotation.Keys.Rect);
This works fine if there is only 1 Field with the same name present in the PDF Document. However, if there are two fields both named "FirstName", even if they are on separate pages, this seems to remove the "/Rect" and "/P" flags, so I cannot use these to find the position or the page relevant to that field.
Is there any other way to get the position of a Field in the PDF, or any way to activate the "/Rect" and "/P" flags?
Thanks, RBrNx
What Mihai posted fits what I discovered from reverse engineering the PDF via PdfSharp. If there are multiple fields in the same document, they are nested under a parent container, and it is a reference to this parent container which PdfSharp will give you when using the AcroForm.Fields accessor. To get the Page and Rectangle elements for each field, you have to look at the children of that container.
To get the values you are looking for, you'll want to do something like this:
PdfTextField imageField = (PdfTextField)inForm.Fields[elementName];
var fieldRectangles = new List<PdfRectangle>();
if( imageField.HasKids )
{
PdfArray kids = (PdfArray) Elements[Keys.Kids];
foreach( var kid in kids )
{
var kidValues = ((PdfReference) kid).Value as PdfDictionary;
var rectangle = kidValues.Elements.GetRectangle(PdfAnnotation.Keys.Rect);
fieldRectangles.Add(rectangle);
}
}
The page reference element ("/P" tag) is also available from these "Kid" elements.