Document Level (Document Open) Scripts

Open, Event, Global
Printer-Friendly Format

Warning
JavaScript has been turned off for this Browser Window
This page is best viewed with JavaScript turned on

General:

The Document Level scripts are a set of scripts that exist at the top of the Document's JavaScript structure. A PDF can have any number of Document Level scripts. These scripts are the first ones executed when the document is opened in Acrobat or Adobe Reader. In fact, these scripts may actually be run before the document is completely loaded and displayed to the user so care must be taken not to run code in one of these scripts that depends on the document being loaded. For example, any code that affects document pages or creates visual or user interface elements should not be placed in a document script.

Document scripts are used for doing setup operations, performing top level environment testing and defining functions and variables that will be used by other code in the document. It's perfectly acceptable in a Document Level script to define a function that will create a UI element, but it may be risky to run such a function in a Document Level script.

Variables and Functions:

Any variable or function defined in a Document Script (or really, any script in the document) is a member of the document scope. This means that any script inside the document can access the variable or function without qualification, basically just using the variable like it's normally used, such as the script below.
Document Script
    // Define a variable
    var nDoc1Var = 3;
  
    // use variable in any script in document
    b = nDoc1Var + 1;
    // Or use it with the document qualifier (unnecessary)
    b = this.nDoc1Var + 1;

The first two lines seem pretty obvious, but the last line uses the this keyword, which is a document object. All variables and functions defined inside a document script are members of the document, so they are directly accessible through the document object. Of course, inside the document context (scope) the this keyword is not necessary. But the document object is necessary outside the document context.

Accessing a Document Variable or Function Outside Document Scope:

If scripts in a set of documents need to work together, or you are designing an automation script to work with specific documents/forms, then document variables and functions may need to be used outside of the document scope. As mentioned in the previous section, the trick to doing this is to access them through the document object. But it's a bit more complicated than that. Here's some example code from a Trusted Script.
Trusted Script
    // Open Document 
    var oDoc1 = app.openDoc(... Doc1 Path ...);
  
    // Set a variable in the document
    oDoc1.nDoc1Var  = 1;
Acrobat protects scripts inside a document by blocking access to document scope objects from un-trusted contexts. So, the above code will only work if the script is run from a Trusted Context. But for document scripts there is another way.

From a untrusted document context

Early on in the history of Acrobat the idea of trust was a bit fuzzy, but the need for some kind of security became more urgent over time. Now we have fairly well defined concepts of privilege and trust mechanisms, most notably the Trusted Function. However, the first mechanism Adobe introduced was document disclosure. The idea was that a document would disclose itself to expose objects in the document scope. This disclosure has to happen in a document script. It can't be done from outside the document, and it can't be done after the document is already open. After a PDF is disclosed, it is visible in the app.activeDocs array to un-trusted scripts, i.e., scripts in another document.
Document Script
    // Disclose object in this document
    this.disclosed = true;
Script in another document
    // First, find document 1 by looking for the variable defined in that document. 
    // Could also look for document name or other document property
    var oDoc = null;
    for(var i=0;i<app.activeDocs.length;i++)
    {
        if(typeof(a.nDoc1Var) != "undefined")
        { 
            oDoc = a; 
            break;
        }
    }
  
    if(oDoc)
    {// access variables or functions in first document
          var myDocVar = oDoc.nDoc1Var;
    }

Entering/Editing Document Scripts

Document Scripts are accessed from the Document Script toolbutton in the JavaScript tool group. This tool group is not one of the ones normally exposed on the left side tools panel, so you'll need to get it from the Main Tools Listing. Once you have it on the main tools listing you can activate the Document Scripts dialog with the toolbutton shown in the screen shot below.
Document Level (Document Open) Scripts

With this dialog you can add new document scripts, edit an existing script, or delete a script. Use multiple scripts to categorize and organize functionality. This is a convenience, there is no technical reason to have more than one document level script.


For more information see these videos

(Member only content)
  • Finding Scripts in Acrobat (14:45)
  •     Entering and Using Document Level Scripts (11:55)
    •     Document Level Script Examples (7:45)
    •     Doc Level Example - Order Form
  • Example: Using a Function in a PDF (14:19)
    •  Sample Files: Code re-use examples

Alert User if Acrobat/Adobe Reader Version is too Low
Basic Document Level Scripts

Skill Level: Beginner Environment: Acrobat JavaScript
Applies To: PDF Document Script Location: Document Level Script
Acrobat Ver.: 4.0 and later Reader: Yes

PDF features and Acrobat JavaScript have changed dramatically since Acrobat was first released and continue to change with each new version. Use this script if your PDF requires a viewer of a specific version or later.

How It Works:
The script checks the Acrobat version number and then displays an alert message to the user if the version number is too low.

To Use this Script change the version number that's tested.

Modify this script by changing the message displayed to the user or actions taken by the script for an incorrect version number. The test can also be modified to target a specific version number, or number range.

Code:
if(app.viewerVersion < 7)
{// Acrobat/Reader Version 6 and earlier are unacceptable
   app.alert("This Document Requires Acrobat/Reader 7.0 or later for Proper Operation");
}


Display a popup alert on open
Basic Document Level Scripts

Skill Level: Intermediate Environment: Acrobat JavaScript
Applies To: PDF Document Script Location: Document Level Script
Acrobat Ver.: 4.0 and later Reader: Yes

Document Scripts may run before the document is fully loaded. Because of this behavior, there are many operations that may not work properly in a document script. Whether or not an operation works depends on timing issues in Acrobat, the document size, and the user's system. So this is not a predictable phenomenon. One of the most common types of problem operations is displaying a user interface option, such as a popup dialog, menu, or floating toolbar. This example script will mitigate the issue by using a timer delay to display a simple alert box.

How It Works:
This document level script defines a function that displays an alert box with yes and no buttons. If the user chooses no the document is closed. The last operation in the script starts a timer that executes the function after one second. One Second is long enough for most documents to completely load.

To Use this Script Open the document

Modify this script by switching out the Alert popup with another operation.

Code:
function ShowDocAlert()
{
   if(3 == app.alert("Do you agree to the terms of use for this  document?",2,2))
        this.closeDoc();
}
  
app.setTimeOut("ShowDocAlert()",1000);


Alert User if PDF Opened in Adobe Reader
Basic Document Level Scripts

Skill Level: Beginner Environment: Acrobat JavaScript
Applies To: PDF Document Script Location: Document Level Script
Acrobat Ver.: 3.01 and later Reader: Yes

There are many JavaScript operations that work in Acrobat Professional and Standard, but either require special enabling to work in Adobe Reader or will not work in Adobe Reader at all. These operations are suitable for inter-office documents where the user is expected to have Acrobat, but not for public distribution. Use this script on any PDF that fits these parameters.

How It Works:
The script checks the Acrobat viewer type and then displays an alert message to the user if the type is "Reader".

Modify this script by changing the message displayed to the user or actions taken by the script. The test can also be modified to test for Acrobat Standard or for the many odd variations that Adobe has created over the years. This script can also be modified to test for any of the old Adobe Servers, or LiveCycle servers. These servers can open a PDF and run JavaScript, which may be a big problem for some scripts on the document.

Code:
if(app.viewerType == "Reader")
{
   app.alert("This Document Requires Acrobat Professional or Standard.  It cannot be used in Adobe Reader");
}


Expire PDF on a Specific Date
Document Control

Skill Level: Intermediate Environment: Acrobat JavaScript
Applies To: PDF Document Script Location: Document Level Script
Acrobat Ver.: 4.0 and later Reader: Yes

A Document Level script can be used to close a document when a certain date has been reached. This is a simple expiration method with minimal security and can be beaten by anyone who knows PDF and Acrobat JavaScript well enough to understand what's going on. But for most users it's sufficient.

How It Works:
The first part of the script acquires the current and final dates and compares them using Core JavaScript methods. The final, or expiration date, is hard coded into the script. If the final date is earlier than the current date the user is given a popup message and the document is closed. It's important to apply security to the PDF so a user can't see the scripts. However, this part can be beaten by simply turning off JavaScript. The second optional part of the "if" statement, i.e. the "else" part, is designed to make beating the method more difficult.

To use the second part of the script a page size watermark must be applied to the entire document so that all the pages are completely covered. This second part finds the Watermark (OCG) Layer and hides it so the document can be viewed. But before this will work properly, some work needs to be done on the Watermark Layer.
  1. Use the first part of the "Design" code given below to make the Watermark Layer visible in the "Layers" tab.
  2. In the Layers tab right click on the Watermark layer and select Properties to display the Layers properties dialog
  3. On the Layer's properties dialog select "Visible When On" for the "Visibility" drop-down list.
  4. Use the second part of the "Design" code given below to remove the Watermark Layer from the "Layers" tab.
  5. Add the Document Level Script to the PDF
  6. Apply security to the document (after adding the script) and save it.
That's it.

Modify this script by changing the message displayed on expiration.

Code: Design Code
// Copy this script to the Acrobat JavaScript Console 
 
// Part 1: make Watermark visible in the Layers Tab
this.setOCGOrder(this.getOCGs());
 
// Part 2: Remove all Layers from the Layers Tab
this.setOCGOrder([]);
 
Code:Document Level Script
// Copy this script to a document level script
// Get Current Date
var curDate = new Date();
// Get Final date
var finalDate = new Date("3/20/2009");
// Compare Dates
if(finalDate.getTime() < curDate.getTime())
{ // Past closing Date, expire document
   app.alert("This document is no longer valid.  Please contact the author");
   this.closeDoc(true);
}
// Only use code below this point if you have followed the instructions 
// in the How To section above for adding a watermark to the PDF
else
{ // allow document to be shown
  // This part is optional, and just adds better security
  // Document is obscured by a opaque watermark that covers all the pages
  var ocgs = this.getOCGs();
  for(var i=0;i<ocgs.length;i++)
  {
     if(ocgs[i].name == "Watermark")
        break;
  }
  // Hide watermark so document can be seen
  ocgs[i].state= false;
}

Display Current Date/Time on Document
Basic Document Level Scripts

Skill Level: Beginner Environment: Acrobat JavaScript
Applies To: PDF Document Script Location: Document Level Script
Acrobat Ver.: 4.0 and later Reader: Yes

When the Document is opened, the current date and/or time is displayed in the header/footer.

How It Works:
The date/time text is displayed in a Text Field on one or more pages in the PDF. The first part of the script acquires the current date/time and formats it for display. The second part of the script applies the date/time text to a text field.

To Use this Script, add a Text Field to the PDF and name it "CurrentDocDate". Make this field ReadOnly and position it in a convenient location (top or bottom of page). Then duplicate the field to all pages where the date/time will be displayed. It's a good idea to make sure the field looks good (font size, color, border, etc.) and is large enough before duplicating it.

Modify this script by changing the date/time format.

Code:
// Get and Format Date
var currDate = new Date();
var strDate = util.printd("h:MMtt, ddd mmm d, yyyy", currDate);
 
// Display date on pages
this.getField("CurrentDocDate").value = strDate;

Auto-Increment Visible Form ID Each Time PDF is Opened
Intermediate Document Level Scripts

Skill Level: Intermediate Environment: Acrobat JavaScript
Applies To: PDF Document Script Location: Document Level Script
Acrobat Ver.: 4.0 and later Reader: Yes

When the PDF is opened, a sequential Form ID is displayed in the header/footer. This ID is incremented each time the document is saved and reopened. This mechanism is useful for forms that require a unique ID and are used repeatedly from the same location.

How It Works:
The sequential ID is stored in a form field on the form so the PDF must be saved back to the same location for this technique to work. If more than one person uses the form then it should be opened and saved to a network folder accessible to everyone. This technique will not work for generally distributed forms. But, it will work for forms displayed in Adobe Reader if the form is Reader Rights Enabled with Acrobat 8 Professional

To Use this Script, add a Text Field to the PDF and name it "SeqFormID". If desired, place a seed value in the field. This example uses a pure number, so place any number in the field. Make this field ReadOnly and position it in a convenient location (top or bottom of page). Then duplicate the field to all pages where the Form ID will be displayed. It's a good idea to make sure the field looks good (font size, color, border, etc.) and is large enough before duplicating it.

Modify this script by changing format and the method for incrementing the Form ID. This technique can be generalized for use with distributed forms by acquiring the ID from an internet source or by using a random number technique to generate the number.

Code:
// Get and increment Form ID
this.getField("SeqFormID").value++;