How to run a document-level javascript?
Copy link to clipboard
Copied
I am trying to run a script that will extract all field names, their location, page, and type. How and exactly where would I add this script? I tried going to:
Tools > JavaScript > Document JavaScripts > Add
But this does not allow me to run a scrip, only to add or edit one. Can someone please help or point me to the documentation? Thanks.
Here is my script given by chat GPT:
function Extract()
{var allFields = this.getFields();
var fieldInfo = [];
for (var fieldName in allFields) {
var field = allFields[fieldName];
var rect = field.rect;
fieldInfo.push({
"Name": field.name,
"Type": field.type,
"Page": field.page + 1, // Acrobat's page index starts at 0, so adding 1 to make it human-readable
});
}
if (fieldInfo.length > 0) {
var output = "Name,Type,Page\n";
for (var i = 0; i < fieldInfo.length; i++) {
var info = fieldInfo[i];
output += info.Name + "," + info.Type + "," + info.Page + "\n";
}
// Save the CSV string to a file.
var file = new File(app.activeDocument.path + ".csv");
file.open("w");
file.write(output);
file.close();
} else {
console.println("No fields found.");
}
}
Copy link to clipboard
Copied
To run the code you need to call the function, like this:
Extract();
You can do so from a button field, or even from the JS Console.
If you want it to execute when the file is opened add that line after your current code.
Copy link to clipboard
Copied
Thanks for the response, but this is not clear enough to me. I've researched for several hours yesterday, and can only find snippets of help. Can you walk me though as a total beginner what specific options, and what I need to change from my script? Do I just add a semicolon somewhere? I don't get it.
Copy link to clipboard
Copied
Before doing all of that, maybe describe what you want to achieve...
Copy link to clipboard
Copied
The code you posted is missing a lot more than just a semi-colon. To write a script for Acrobat, you have to use the Acrobat JavaScript model. Making stuff up doesn't work (which is what chat gpt does).
Watch this video:
https://www.pdfscripting.com/public/images/Free_Videos/BeginJS_InAcrobat_Free_mp4.cfm
And read this:
https://www.pdfscripting.com/public/PDF-Form-Scripting.cfm
Take a look at the free "Find Required Fields" tool here:
https://www.pdfscripting.com/public/Free_Acrobat_Automation_Tools.cfm
It'll provide the base code for the tool you want. And it's an automation script, not a document script.
So read this as well:
https://www.pdfscripting.com/public/Automating-Acrobat.cfm
Use the Acrobat JavaScript Reference early and often

