Using JavaScript To Add JavaScript to a PDF Part 1
Using JavaScript instead of the Acrobat user interface can automate the process of adding scripts to PDFs
There are several places you can add JavaScript to a PDF file:
A document-level script that runs when the PDF is opened.
A page action script that runs when the page is opened or closed.
A document action script than runs during one of the following events:
1)Â Â Â Before the document closes
2)Â Â Â Before the document saves
3)Â Â Â After the document saves
4)Â Â Â Before the document prints
5)Â Â Â After the document prints
A bookmark
A link
A form field
While these scripts can be added through the Acrobat Pro user interface (UI), they can also be added using JavaScript. By using JavaScript the process can be automated using a custom toolbar button, a custom menu item, running the script in the console, or creating an Action that runs a JavaScript, thereby allowing the script to be added to an entire batch of PDF documents.
Take the Acrobat Pro/JavaScript eLearning Course Acrobat Like a Pro
Script Adding Methods
In all these examples doc is a variable representing a document object.
Document-level Script:Â doc.addScript()
This method takes two mandatory input parameters:
1)Â Â Â cName (the name of the script to be added).
2)Â Â Â cScript (the JavaScript to be executed).
The cScript parameter is a literal expression so the entire JavaScript must be enclosed in quotes. Since I use double quotes whenever quotes are required in my scripts, I used single quotes for the cScript parameter to avoid conflicts with quotes. For example, the following script will cause an error (SyntaxError: missing ) after argument list) because the first quotation mark inside the app.alert() method will be interpreted as the closing quote for the cScript parameter:
this.addScript("My Script", "app.alert("The document just opened.")");
The following script will run correctly:
this.addScript('My Script', 'app.alert("The document just opened.")');
In the error example, an alternative correction method is to escape the quotes inside the app.alert method like this:
this.addScript("My Script", "app.alert(\"The document just opened.\")");
In my opinion, it is much easier to use single quotes for the input parameters. I use the single quote trick for all script adding methods discussed in this post. I encourage you to try this by opening a PDF, running the script in the console, saving the PDF, and re-opening it. You should get a popup alert "The document just opened".
Another cautionary note regarding the sScript parameter is that you can't have line breaks in the cScript without putting each line in quotes and concatenating them with a plus sign. Scripts can get pretty lengthy, making them difficult to follow without line breaks. This script will cause an error (SyntaxError: unterminated string literal):
this.addScript('My Script',
'app.alert("This is the first line of the script");
app.alert("This is the second line of the script");
app.alert("This is the third line of the script");')
This script will not cause an error (\r separates the lines in the resulting script):
this.addScript('My Script',
'app.alert("This is the first line of the script");\r'+
'app.alert("This is the second line of the script");\r'+
'app.alert("This is the third line of the script");')
Using the same PDF as the previous example, run the script above in the console and save the PDF. When you re-open it you should get three popup alerts in a row. Because the cName parameter ("My Script") is the same as the previous one, the second script will overwrite the first script in the document.
To view the script, type JavaScript in the Tools tab search field and select Document JavaScripts:
Page Action Script – doc.setPageAction();
Some people use a page open action script on the first page of a document, instead of a document level script. This is fine for a one-page document. If there are multiple pages, however, the script will run every time the user goes to (Open cTrigger) or leaves (Close cTrigger) the first page , not just once, when the document is opened. Be aware of this fact to avoid unintended consequences. The doc.setPageAction() method takes three mandatory input parameters:
1)Â Â Â nPage (the 0-based page number to which the script will be added)
2)Â Â Â cTrigger (the trigger for the action, either Open or Close)
3)Â Â Â cScript (the JavaScript to be executed)
Example:
this.setPageAction(0, 'Open', 'app.alert("Page one just opened.");');
Open a PDF and run the script above in the console, then save the PDF. The alert will appear every time the document is opened, if the document is set to open to page one. The alert will also appear every time the focus goes to page one in a multi-page document.
this.setPageAction(0, 'Close', 'app.alert("Page one just closed.");');
The script above will run every time the user exits page 1, including when the PDF is closed.
To view the script, open the pages panel, right-click on the page, and select Properties. In the Actions tab, select the JavaScript and click Edit.
Document Action Script – doc.setAction()
This script takes two mandatory input parameters:
1)    cTrigger – The name of the trigger for the action.
2)    cScript – The script to be executed.
There are five possible cTrigger parameters that determine when the script will run:
1)Â Â Â WillClose (before the document closes)
2)Â Â Â WillSave (before the document saves)
3)Â Â Â DidSave (after the document saves)
4)Â Â Â WillPrint (before the document prints)
5)Â Â Â DidPrint (after the document prints)
Notice there is no didClose trigger. At this point the document is no longer open so it can't execute a script. The following examples will add a popup alert for the five actions. The alert messages will help you understand when these scripts will execute.
this.setAction('WillClose', 'app.alert("The document will now close.", 1);');
this.setAction('WillSave', 'app.alert("The document will now save. ", 1);');
this.setAction('DidSave', 'app.alert("The document just saved.", 1);');
this.setAction('WillPrint', 'app.alert("The document will now print.", 1);');
this.setAction('DidPrint', 'app.alert("The document just printed.", 1);');
If you run any of those scripts in the console, then save the document, the scripts will run when any of those actions occur. I like to use the app.alert() method for demonstration purposes and testing, but you can execute any script in the document action. A more practical example might be to add or make visible a field, watermark, or time stamp as a WillPrint action. You could then remove it in the DidPrint action.
Example
//adds the script that adds a field before printing
this.setAction('WillPrint',
//Tests whether the field "Message" does not exist
'if(!this.getField("Message"))\r'+
//If true, add the field
'{\r'+
'var f=this.addField("Message","text",0,[0,792,612,792-36])\r'+
' f.fillColor=["RGB",0.635,0.016,0.031];\r'+
'f.alignment="center";\r'+
'f.textFont="Helvetica-Bold";\r'+
'f.textColor=color.white; \r'+
'f.value="www.pdfautomationstation.com";\r'+
'}');
//adds the script that removes the field after printing
this.setAction('DidPrint',
//Test whether the field "Message" exists
'if(this.getField("Message"))\r'+
//If true, remove the field
'{\r'+
'this.removeField("Message");\r'+
'}');
If you run the script above in the console it will add the two action scripts to the document. When the user prints the document, it will print with a red field across the top of page one with white letters that reads www.pdfautomationstation.com. The user will only see this field on the printed page. Even if the printer dialog is opened, the field will not be visible in the page view in the dialog because the Print button has not been clicked yet. As soon as it is clicked the document with the field is sent to the printer, the print dialog closes, and the field is removed from the document.
To view the script, type JavaScript in the tool search, select JavaScript, then click Document Actions on the JavaScript toolbar:
Select the action then click edit.Â
The three locations to add JavaScript by using JavaScript were all document locations. In the next post I will discuss how to add JavaScript to form fields using JavaScript
I'll see you next week for Using JavaScript To Add JavaScript to a PDF Part 2.