Automatically add buttons to a PDF

Learn how to use Acrobat and JavaScript to automate the task of adding buttons to your PDF documents.

By Thom Parker – June 20, 2007

 

Level: Intermediate
Acrobat 7 and Later
Prerequisites: Familiarity with Acrobat and Acrobat JavaScript

Acrobat automation with Acrobat JavaScript can seriously short circuit the task of manually adding buttons to your PDF documents, especially large, non-form documents. But if it’s not a form, why add buttons to a PDF? Answer: To make your document easier to use. A button is a simple, easy-to-use, and familiar interactive feature that can significantly increase document usability. The most common buttons added to a PDF are used for navigation, from simple Next and Previous Page buttons to complex popup menus. There are also many other usability features that can be implemented with a button.

Sure, you can manually add buttons to a PDF with Acrobat Professional, but this can be a time-consuming process. If your business frequently provides information to clients in the form of a PDF (portfolios, reports, manuals, brochures, work product, and so on), you need a fast, easy way to fix up these documents. Automation with Acrobat JavaScript is the answer.

Basic script for adding a button to a PDF

The first building block to our automation script is a slightly generic function for adding a single button to a single page in a PDF. For this example, the button will implement a "Next Page" feature and be placed in the lower-left corner of the page. It's generic because the function can place the button on any page. The actual page number is one of the parameters passed into the function by the main script:

// Button Creation Script function
CreateMyButton(cName, nPage) {
	// Acquire the crop box (visible area) for the current page
	var pgRect = this.getPageBox("Crop", nPage);
	// Build Button Rectangle in lower left corner of page
	var fldRect = []; fldRect [0] = pgRect[0] + 36;
	// 1/2 inch from left side
	fldRect [1] = pgRect[0] + 56;
	// 20 points high
	fldRect [2] = pgRect[0] + 72;
	// 1/2 inch wide
	fldRect [3] = pgRect[0] + 36;
	// 1/2 inch from bottom
	// Create Button on page
	var oFld = this.addField( cName , "button", nPage, fldRect);
	// Setup Button's Properties
	if(oFld != null) {
		oFld.buttonSetCaption("Next");
		oFld.borderStyle = border.b;
		// Beveled edges
		oFld.strokeColor = color.blue;
		// Border Color
		oFld.textColor = color.black; oFld.lineWidth = 1;
		// Thin Border
		oFld.setAction("MouseUp", "this.pageNum++");
		// Navigation
	}
	return oFld;
}

Let’s examine how this code works. At the very top we can see that two arguments are passed in, cName and nPage. These parameters represent the variable parts of the function. They are the name that will be given to the button field and the page number on which to create it. The main script will need to pass these arguments in. You can try it now from the JavaScript Console. First, open any PDF (preferably a scratch document you’re not worried about changing), then copy and paste the function code above into the Console. Next, enter the JavaScript for calling the function:

CreateNextButton("MyNextButt", this.pageNum);

When this code runs, it will place a button in the lower-left corner of the current page of the currently open document.

The calculation for finding the location of the lower-left corner of the page starts with a line of this code for acquiring the page’s Crop Box:

var pgRect = this.getPageBox("Crop", nPage);

The Page’s Crop Box is a rectangle describing the visible area of the page (for more info see this article “Finding Page Boundaries”). In Acrobat JavaScript, a rectangle is an array of four numbers giving the left, top, right and bottom edges of a box, respectively.

In the following code, a new rectangle is created for placing the button. The edges of the new rectangle are calculated as offsets from the boundaries of the page. The offset values are in points. In the PDF world, there are 72 points/inch, so 36 points is the same as a half inch.

Once the button rectangle is found, the button can be created with this line of code:

var oFld = this.addField(cName , "button", nPage, fldRect);

The doc.addField() function has four input parameters. All must be present and in the correct order.

  • The name of the field, used to acquire the field object at a later time.
  • The type of field being created.
  • The page number on which the field will be placed.
  • The rectangle providing the position and size of the field.

This function creates a button with default parameters (border color, font, and so on). If we want the button to look and act a certain way, we have to write some more code. This is done in the last section of the CreateMyButton()function starting with:

if(oFld != null)

The oFld variable is the actual button-field object. It’s returned by the doc.addField() function. If there was an error creating the field, oFld would be null. This if statement tests oFld to make sure a field was in fact created, and only then are the button parameters set.

Most of the button’s properties are set with constant, pre-defined values, such as border.b for creating a beveled outline, and color.blue for creating a blue border. These constants are documented in the Acrobat JavaScript Reference. But two of the button’s features are set with a function. These are the caption displayed on the button and the JavaScript code the button will execute. The button’s action is probably the most important thing about it. This action determines the button’s functionality, so let’s take a closer look.

Setting a button’s Action

From the Acrobat user interface, several action types can be applied to a button, such as “Go to a page view,” “Open a file” and many others. But an automation script can only set one action type, “Run a JavaScript.” So if the addition of buttons to a document is going to be automated, we have to know if the button action can be written with JavaScript. Fortunately, Acrobat JavaScript is very rich and just about any action that can be set through the Acrobat user interface can be replicated with a script.

Another part of running an action from a button is the trigger. The trigger is what triggers the execution of the action. For a button we have six possible triggers: “MouseUp,” “MouseDown,” “MouseEnter,” “MouseExit,” “OnFocus,” and “OnBlur.” The typical trigger used for a button action is “MouseUp.” The other triggers are normally used to create visual effects.

The Field.setAction() function sets the JavaScript action for a field. It has two input parameters: the trigger and the action script. This is shown in the second-to-last line of code in CreateMyButton().

oFld.setAction("MouseUp", "this.pageNum++;");

The script is a simple one-liner that increments the current page number, so the whole script easily fits into the function call. However, button scripts can be large and complex, so this is not always a practical method. There are a couple ways to handle large scripts. One method is to place the code into a string variable. In the code below, the simple one line “Next Page” code is expanded into a more explicit two-line script and assigned to the cScript variable. Then the cScript is used in the oFld.setAction() call:

var cScript = "var nPgNum = this.pageNum + 1;\n"; cScript += "this.pageNum = nPgNum";
oFld.setAction("MouseUp", cScript);

Notice the new line-escape sequence in the first line, “\n.” This makes the code look nice when it’s opened from the Acrobat user interface; it has no affect on functionality.

Another option for handling large code blocks is to write them into a Document Level function, then place the call to this function in the Field.setAction() function. Use the Doc.addScript() function to place the function in a Document Level script:

var cScript = "function IncrPage() { this.pageNum++; }";
this.addScript("MyFuncts", cScript); oFld.setAction("MouseUp", "IncrPage();" );

Automation scripting

There are two kinds of automation scripts: single document and batch (multiple documents). Scripts for acting on a single document are placed into a custom Acrobat toolbar button or menu item. These user-interface items are created with Folder-level scripts. Folder-level scripts are files with the “.js” file extension, and they are placed in a specific Acrobat Folder. Batch scripts are entered through the batch- processing dialogs. The good news is that in either case, the code is usually the same. Below is the code for the main script of our example. It can be run from the Console Window or placed in either a Folder Level or Batch script. It will run the same for all of them without any changes. Take a look at the above referenced articles to get information on putting the script into any of these locations.

// Main Automation Code for placing a Next Page button
// on every page (except the last page) of a document
for(var nPg = 0 ; nPg < this.numPages-1 ; nPg++){
	CreateMyButton("NextButt", nPg);
}

This code and the CreateMyButton()function can be modified to add different kinds of buttons in different locations on the page. You can even get fancy and place icons on the buttons. You’ll find information on all the various Acrobat JavaScript features that can be used to create your button in the Acrobat JavaScript Guide and Acrobat JavaScript Reference at the link below. Look under the “Documentation” tab at www.adobe.com/devnet/acrobat.

Below is a folder-level script that implements this code in an Acrobat toolbar. You’ll find information on how to locate this folder in “Entering Folder level scripts.”

CreateMyButton script
Download this JavaScript file into Acrobat’s JavaScript folder.
Download [JAVASCRIPT: 6.5 KB]



Related topics:

JavaScript

Top Searches:


0 comments

Comments for this tutorial are now closed.

Comments for this tutorial are now closed.