PDF Automation Station

PDF Automation Station

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

David Dagley's avatar
David Dagley
Feb 24, 2024
∙ Paid
Share

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.

Get the course above, and a suite of automation tools for FREE with a Professional subscription.


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 post is for paid subscribers

Already a paid subscriber? Sign in
© 2025 David Dagley
Privacy ∙ Terms ∙ Collection notice
Start writingGet the app
Substack is the home for great culture