Product: PDFTron .NET x64
Product Version: 9.1.0
Getting a Page Number Based on a Field?
I am currently using the PDFTron SDK to set form values based on some data and a field mapping schema provided in XML. This requires me to loop through the XML data nodes, retrieve the corresponding mapping value, and then retrieve the corresponding Field from the PDF document in order to set its value.
We currently have a “cursor” sign widget that allows the user to draw their signature, which is then saved as a PNG image. This widget is on an HTML page from which data must be transferred/converted to PDF.
I’m using the Stamper class to stamp this image onto the middle of the signature field. I can get all the relevant position data from Field.GetUpdateRect(), but I can’t figure out an easy and efficient way to get the page number for a given field.
The only code I’ve been able to cobble together requires looping through every control on every page until I find a match for the field name (see below). Is there an easier and more efficient way to do this, given that I’ve already retrieved the Field object?
private int GetPageNumberFromFieldName(string fieldName, PDFDoc srcDoc) {
int pageNum = -1;
int pageCount = srcDoc.GetPageCount();
for (int pageNo = 1; pageNo <= pageCount; pageNo++) {
pdftron.PDF.Page page = srcDoc.GetPage(pageNo);
if (page != null) {
//Get number of controls on the page
int fieldCount = page.GetNumAnnots();
//loop through all those fields...
for (int loop = 0; loop < fieldCount; loop++) {
Annot annot = page.GetAnnot(loop);
if (!annot.IsValid()) {
continue;
}
//if it is valid widget control
if (annot.GetType() == Annot.Type.e_Widget) {
pdftron.PDF.Annots.Widget w = new
pdftron.PDF.Annots.Widget(annot);
Field field = w.GetField();
if (field != null && field.GetName() == fieldName) {
return pageNo;
}
}
}
}
}
return pageNum;
}