Skip to main content
Anantha Prabu G
Legend
November 8, 2024
Question

Issue with Field Name Order in PDF Script

  • November 8, 2024
  • 1 reply
  • 279 views

Hi everyone,

I'm using a PDF script that works well for ordering the field names by "Order Tabs by Structure" (exact order). However, I've noticed that for some of the order of the field names changes unexpectedly.

Has anyone encountered this issue before? Is there a way to ensure that the field names always stay in the correct order, regardless of the PDF structure or any changes in the document?

Any help or suggestions would be greatly appreciated!

Thanks in advance!
Script is below:

var fieldArray = [];
for (var i = 0; i < this.numFields; i++) {
    var field = this.getField(this.getNthFieldName(i));
    var fontSize = field.textSize;
    var fontName = field.textFont;
    var rect = field.rect; // Array of coordinates [left, bottom, right, top]
    var width = (rect[2] - rect[0]) / 72; // Convert points to inches
    var height = Math.abs((rect[3] - rect[1]) / 72); // Convert points to inches and use absolute value
    fieldArray.push({ name: field.name, tooltip: field.userName, fontSize: fontSize, fontName: fontName, width: width, height: height, type: field.type, top: rect[3], left: rect[0], pageNum: field.page });

}

// Sort the fields by page number, then by their top position (from top to bottom), then by left position (from left to right)
fieldArray.sort(function(a, b) {
    if (a.pageNum === b.pageNum) {
        if (b.top === a.top) {
            return a.left - b.left;
        }
        return b.top - a.top;
    }
    return a.pageNum - b.pageNum;
});

console.println("Field names, tooltips, font sizes, font names, widths (inches), and heights (inches) in the document:");
for (var j = 0; j < fieldArray.length; j++) {
    var fieldInfo = fieldArray[j];
    var widthText = fieldInfo.type === "checkbox" ? fieldInfo.width.toFixed(2) + " inches" : "width";
    console.println(fieldInfo.name + "; " + fieldInfo.tooltip + "; " + fieldInfo.fontSize + "; " + fieldInfo.fontName + "; " + widthText + "; " + fieldInfo.height.toFixed(2) + " inches");
}
This topic has been closed for replies.

1 reply

try67
Community Expert
Community Expert
November 8, 2024

The initial order doesn't matter, since you're sorting them afterwards. I think your issue is in the sort function. Namely, in your assumption that the page property is always a number. It isn't. It can also be an array of numbers, if there is more than one instance of a field in the file. You need to take that into account in your code. Also, this array doesn't have to be sorted from lowest to highest, either.