|
|
Adds a menu item to a menu.
Note:Starting Acrobat X, the number of top-level menu items has been reduced. The menu items available from Acrobat X onwards are: File, Edit, View, Window, and Help. If any of your previous scripts referred to a top-level menu item that no longer exists, the reference will not work.
Note:This method can only be executed during application initialization or console events. See the event object for a discussion of JavaScript events.
See also the addSubMenu, execMenuItem, hideMenuItem, and listMenuItems methods.
cName |
The language-independent name of the menu item. This name can be used by other methods (for example, hideMenuItem) to access the menu item. |
cUser |
(optional) The user string (language-dependent name) to display as the menu item name. If cUser is not specified, cName is used. |
cParent |
The name of the parent menu item. Its submenu will have the new menu item added to it. If cParent has no submenu, an exception is thrown. Menu item names can be obtained with the listMenuItems method. |
nPos |
(optional) The position within the submenu to locate the new menu item. The default behavior is to append to the end of the submenu. Specifying nPos as 0 adds the menu to the top of the submenu. Beginning with ( The nPos parameter is ignored in certain menus that are alphabetized. The alphabetized menus are
Note:When nPos is a number, nPos is not obeyed in the Tools menu. A menu item introduced into the Tools menu comes in at the top of the menu. nPos is obeyed when it is a string referencing another user-defined menu item. |
cExec |
An expression string to evaluate when the menu item is selected by the user. Note:Beginning with |
cEnable |
(optional) An expression string that is evaluated to determine whether to enable the menu item. The default is that the menu item is always enabled. This expression should set event.rc to false to disable the menu item. |
cMarked |
(optional) An expression string that determines whether the menu item has a check mark next to it. The expression should set event.rc to false to uncheck the menu item and true to check it. The default is that the menu item is not marked. |
(optional,
bPrepend is useful when the named item is the first item in a group. |
At the top of the File menu, add a menu item that opens an alert dialog box displaying the active document title. This menu is only enabled if a document is opened.
app.addMenuItem({ cName: "Hello", cParent: "File",
cExec: "app.alert(event.target.info.title, 3);",
cEnable: "event.rc = (event.target != null);",
nPos: 0
});
Place two menu items in the File menu, one before the Close item and the other after the Close item.
// Insert after the "Close" item (the default behavior)
app.addMenuItem( { cName: "myItem1", cUser: "My Item 1", cParent:
"File", cExec: "_myProc1()", nPos: "Close"});
// Insert before the "Close" item, set bPrepend to true.
app.addMenuItem( { cName: "myItem2", cUser: "My Item 2", cParent:
"File", cExec: "_myProc2()", nPos: "Close", bPrepend: true });
Adds a menu item with a submenu to the application.
See also the addMenuItem, execMenuItem, hideMenuItem, and listMenuItems methods.
Note:Starting Acrobat X, the number of top-level menu items has been reduced. The menu items available from Acrobat X onwards are: File, Edit, View, Window, and Help. If any of your previous scripts referred to a top-level menu item that no longer exists, the reference will not work.
Note:This method can only be executed during application initialization or console events. See the event object for a discussion of JavaScript events.
cName |
The language-independent name of the menu item. This language-independent name is used to access the menu item (for example, for hideMenuItem). |
cUser |
(optional) The user string (language-dependent name) to display as the menu item name. If cUser is not specified, cName is used. |
cParent |
The name of the parent menu item to receive the new submenu. Menu item names can be discovered with listMenuItems. |
nPos |
(optional) The position within the parent’s submenu to locate the new submenu. The default is to append to the end of the parent’s submenu. Specifying nPos as 0 adds the submenu to the top of the parent’s submenu. The nPos parameter is ignored in certain menus that are alphabetized. The alphabetized menus are
Note:When nPos is a number, nPos is not obeyed in the Tools menu. A menu item introduced into the Tools menu comes in at the top of the menu. nPos is obeyed when nPos is a string referencing another user-defined menu item. |
See the newDoc method.
6.0 |
|
|
|
Adds a button to the “Add-on” toolbar of
If there is an active document (for example, docA.pdf) open in
The icon size is restricted to 20 by 20 pixels. If an icon of larger dimensions is used, an exception is thrown.
Note:(
If this method is called from nonprivileged script, the warning “JavaScript Window” appears on the “Add-on” toolbar, which will not be dockable. (See Privileged versus non-privileged context.)
See also removeToolButton.
cName |
A unique language-independent identifier for the button. The language-independent name is used to access the button for other methods (for example, removeToolButton). Note:The value of cName must be unique. To avoid a name conflict, check listToolbarButtons, which lists all toolbar button names currently installed. |
oIcon |
An Icon Stream object. Beginning with |
cExec |
The expression string to evaluate when the button is selected. |
cEnable |
(optional) An expression string that determines whether to enable the toolbutton. The default is that the button is always enabled. This expression should set event.rc to false to disable the button. |
cMarked |
(optional) An expression string that determines whether the toolbutton is marked. The default is that the button is not marked. This expression should set event.rc to true to mark the button. |
cTooltext |
(optional) The text to display in the button help text when the mouse is over the toolbutton. The default is not to have a tool tip. Note:Avoid the use of extended characters in the cTooltext string as the string may be truncated. |
nPos |
(optional) The button number to place the added button before in the toolbar. If nPos is -1 (the default), the button is appended to the toolbar. |
cLabel |
(optional, |
undefined
Create a button from an icon graphic on the user’s hard drive. This script is executed from the console.
// Create a document
var myDoc = app.newDoc();
// import icon (20x20 pixels) from the file specified
myDoc.importIcon("myIcon", "/C/myIcon.jpg", 0);
// convert the icon to a stream.
oIcon = util.iconStreamFromIcon(myDoc.getIcon("myIcon"));
// close the doc now that we have grabbed the icon stream
myDoc.closeDoc(true);
// add a toolbutton
app.addToolButton({
cName: "myToolButton",
oIcon: oIcon,
cExec: "app.alert('Someone pressed me!')",
cTooltext: "Push Me!",
cEnable: true,
nPos: 0
});
app.removeToolButton("myToolButton")
See also the example following util.iconStreamFromIcon.
3.01 |
|
|
|
Displays an alert dialog box.
Note:If this method is called on a button click event using LiveCycle Designer 7 or 8, it appends the title "Warning: JavaScript Window - " in Acrobat 8.
cMsg |
A string containing the message to be displayed. |
nIcon |
(optional) An icon type. Possible values are these: 0 — Error (default) 1 — Warning 2 — Question 3 — Status Note:In Mac OS, there is no distinction between warnings and questions. |
nType |
(optional) A button group type. Possible values are these: 0 — OK (default) 1 — OK, Cancel 2 — Yes, No 3 — Yes, No, Cancel |
cTitle |
(optional, |
oDoc |
(optional, |
oCheckbox |
(optional, cMsg — (optional) A string to display with the check box. If not specified, the default string is “Do not show this message again”. bInitialValue — (optional) If true, the initial state of the check box is checked. The default is false. bAfterValue — When the alert method exits, contains the state of the check box when the dialog box is closed. If true, the check box was checked when the alert box is closed. |
nButton, the type of the button that was pressed by the user:
1 — OK
2 — Cancel
3 — No
4 — Yes
Display a simple alert box:
app.alert({
cMsg: "Error! Try again!",
cTitle: "Acme Testing Service"
});
Close the document with the user’s permission:
// A MouseUp action
var nButton = app.alert({
cMsg: "Do you want to close this document?",
cTitle: "A message from A. C. Robat",
nIcon: 2, nType: 2
});
if ( nButton == 4 ) this.closeDoc();
One document creates an alert box in another document. There are two documents, DocA and DocB, one open in a browser and the other in the viewer.
// The following is a declaration at the document level in DocA
var myAlertBoxes = new Object;
myAlertBoxes.oMyCheckbox = {
cMsg: "Care to see this message again?",
bAfterValue: false
}
The following is a mouse-up action in DocA. The variable theOtherDoc is the Doc object of DocB. The alert box asks if the user wants to see this alert box again. If the user clicks the check box, the alert does not appear again.
if ( !myAlertBoxes.oMyCheckbox.bAfterValue )
{
app.alert({
cMsg: "This is a message from the DocA?",
cTitle: "A message from A. C. Robat",
oDoc:theOtherDoc,
oCheckbox: myAlertBoxes.oMyCheckbox
});
}
3.01 |
|
|
|
Causes the system to play a sound.
Note:On Mac OS and UNIX systems the beep type is ignored.
nType |
(optional) The sound type. Values are associated with sounds as follows: 0 — Error 1 — Warning 2 — Question 3 — Status 4 — Default (default value) |
Raises the execution privilege of the current stack frame such that methods marked secure can execute without security exceptions. For the method to succeed, there must be a frame on the stack representing the execution of a trusted function, and all frames (including the frame making the call) between the currently executing frame and that frame must represent the execution of trust propagator functions.
Use app.endPriv to revoke privilege. The app.trustedFunction method can create a trusted function, and app.trustPropagatorFunction can create a trust propagator function. The term stack frame is discussed following the description of app.trustedFunction.
undefined on success, exception on failure
For examples of usage, see trustedFunction and trustPropagatorFunction.
Presents a file system browser and returns an object containing information concerning the user’s response.
Note:This method can only be executed during a batch or console event. See the event object for a discussion of JavaScript events. See Privileged versus non-privileged context for details.
bSave |
(optional) A Boolean value that, if true, specifies that the file system browser should be presented as it would be for a save operation. The default is false. |
cFilenameInit |
(optional) A string that specifies the default file name for the file system browser to be populated with. |
cFSInit |
(optional) A string that specifies the file system that the file system browser operates on initially. Two values are supported: “” (the empty string) representing the default file system and “CHTTP”. The default is the default file system. This parameter is only relevant if the web server supports WebDAV. |
On success, returns an object that has three properties.
Property |
Description |
---|---|
cFS |
A string containing the resulting file system name for the chosen file. |
cPath |
A string containing the resulting path for the chosen file. |
cURL |
A string containing the resulting URL for the chosen file |
If the user cancels, the return value is undefined. On error, throws an exception.
Browse for a document and report the results to the console.
var oRetn = app.browseForDoc({
cFilenameInit: "myComDoc.pdf",
cFSInit: "CHTTP",
});
if ( typeof oRetn != "undefined" )
for ( var o in oRetn )
console.println( "oRetn." + o + "=" + oRetn[o]);
else console.println("User cancelled!");
If the user selects a file on a WebDAV server, a possible output of this code is given below:
oRetn.cFS=CHTTP
oRetn.cPath=http://www.example.com/WebDAV/myComDoc.pdf
oRetn.cURL=http://www.example.com/WebDAV/myComDoc.pdf
Should the user select a file in the default file system, a typical output of this code is given below:
oRetn.cFS=DOS
oRetn.cPath=/C/temp/myComDoc.pdf
oRetn.cURL=file:///C|/temp/myComDoc.pdf
The script can go on to open the selected file using app.openDoc.
var myURL = (oRetn.cFS=="CHTTP") ? encodeURI(oRetn.cPath) : oRetn.cPath;
var oDoc = app.openDoc({cPath: myURL, cFS: oRetn.cFS});
Note:app.openDoc requires cPath to be an escaped string when retrieving a file from a WebDAV server. See app.openDoc for a brief description and example.
Browse and save a document.
var oRetn = app.browseForDoc({
bSave: true,
cFilenameInit: "myComDoc.pdf",
cFSInit: "CHTTP",
});
if ( typeof oRetn != "undefined" ) this.saveAs({
cFS: oRetn.cFS, cPath: oRetn.cPath, bPromptToOverwrite: false});
5.0 |
|
|
|
Cancels a previously registered interval initially set by the setInterval method.
See also setTimeOut and clearTimeOut.
oInterval |
The registered interval to cancel. |
See setTimeOut.
5.0 |
|
|
|
Cancels a previously registered time-out interval. Such an interval is initially set by setTimeOut.
See also setInterval and clearInterval.
oTime |
The previously registered time-out interval to cancel. |
See setTimeOut.
Revokes any privilege bestowed upon the current stack frame by app.beginPriv. Does not revoke privilege bestowed by the current event.
Related methods are app.trustedFunction, app.trustPropagatorFunction and app.beginPriv.
undefined on success, exception on failure
For examples of usage, see trustedFunction and trustPropagatorFunction.
7.0 |
|
|
|
Presents a modal dialog box to the user. Modal dialog boxes must be closed by the user before the host application can be directly used again.
The monitor parameter specifies a dialog descriptor, which is a generic object literal that consists of a set of handler functions for various events and a set of properties that describe the contents of the dialog box.
Dialog box items are identified by an ItemID, which is a unique 4-character string. An ItemID is necessary only if the element must be referred to elsewhere in the dialog box description (for example, to set or get a value for the element, to add a handler for the element, or to set a tab order including the element).
Note:To distinguish
monitor |
An object literal. It consists of several handlers (see Dialog box handlers) and a description property that describes the dialog box elements (see description property). |
inheritDialog |
(optional) A Dialog object that should be reused when displaying this dialog box. It is useful when displaying a series of dialog boxes (such as a wizard) to prevent one from disappearing before the new one is displayed. The default is not to reuse a dialog box. |
parentDoc |
(optional) A Doc object to use as the parent for this dialog box. The default parent is the |
A string, which is the ItemID of the element that caused the dialog box to be dismissed. The return value is “ok” or “cancel” if the dismissing element is the ok or cancel button.
Note:Debugging is disabled while a modal dialog box created by app.execDialog is active.
The dialog box handlers are called when specific dialog box events occur. Each handler is optional and is passed a Dialog object that can be used to query or set values in the dialog box. The supported handlers are listed in the table that follows.
Dialog box handler |
Description |
---|---|
initialize |
Called when the dialog box is being initialized. |
validate |
Called when a field is modified to determine if the value is acceptable (by returning true) or unacceptable (by returning false). |
commit |
Called when the OK button of the dialog box is clicked. |
destroy |
Called when the dialog box is being destroyed. |
ItemID |
Called when the dialog box element ItemID is modified. For a text box, it is when the text box loses focus. For other controls, it is when the selection changes. If ItemID is not a JavaScript identifier, the name must be enclosed in double quotes when the method is defined, as in the following example. "bt:1": function () { .... } If ItemID is a JavaScript identifier, the double quotes are optional. For example, the following are both correct. "butn": function () { .... } butn: function () { .... } |
The description property is an object literal that contains properties describing the dialog. Its elements property specifies the elements of the dialog box, and each of the elements in turn can have an elements property describing subelements.
The dialog properties at the root level of the description property are listed in the table that follows.
Property |
Type |
Description |
---|---|---|
name |
String |
The title bar of the dialog box, which should be localized. |
first_tab |
String |
An ItemID for the dialog box item that should be first in the tab order. This dialog box item will also be active when the dialog box is created. This property is required for setting up a tabbing order. See the next_tab property defined below. |
width |
Numeric |
The width of the dialog box in pixels. If no width is specified, the combined width of the contents is used. |
height |
Numeric |
The height of the dialog box in pixels. If no height is specified, the combined height of the contents is used. |
char_width |
Numeric |
The width of the dialog box in characters. If no width is specified, the combined width of the contents is used. |
char_height |
Numeric |
The height of the dialog box in characters. If no height is specified, the combined height of the contents is used. |
align_children |
String |
The alignment for all descendants. Must be one of the following values: “align_left”: Left aligned “align_center”: Center aligned “align_right”: Right aligned “align_top”: Top aligned “align_fill”: Align to fill the parent’s width; may widen objects. “align_distribute”: Distribute the contents over the parent’s width. “align_row”: Distribute the contents over the parent’s width with a consistent baseline. “align_offscreen”: Align items one on top of another. |
elements |
Array |
An array of object literals that describe the dialog box elements contained within this dialog (see elements property). |
A dialog box elements property specifies an object literal with the following set of properties.
Property |
Type |
Description |
---|---|---|
name |
String |
The displayed name of the dialog box element, which should be localized. Note:This property is ignored for the “edit_text” type. |
item_id |
String |
An ItemID for this dialog box, which is a unique 4-character string. |
type |
String |
The type of this dialog box element. It must be one of the following strings: “button” - A push button. “check_box” - A check box. “radio” - A radio button. “list_box” - A list box. “hier_list_box” - A hierarchical list box. “static_text” - A static text box. “edit_text” - An editable text box. “popup” - A pop-up control. “ok” - An OK button. “ok_cancel” - An OK and Cancel Button. “ok_cancel_other” - An OK, Cancel, and Other button. “view” - A container for a set controls. “cluster” - A frame for a set of controls. “gap” - A place holder. |
String |
An ItemID for the next dialog box item in the tab order. Note:Tabbing does not stop at any dialog box item that is not the target of the next_tab (or first_tab) property. Tabbing should form a circular linked list. |
|
width |
Numeric |
Specifies the width of the element in pixels. If no width is specified, the combined width of the contents is used. |
height |
Numeric |
Specifies the height of the element in pixels. If no height is specified, the combined height of the contents is used. |
char_width |
Numeric |
Specifies the width of the element in characters. If no width is specified, the combined width of the contents is used. |
char_height |
Numeric |
Specifies the height of the element in characters. If no height is specified, the combined height of the contents is used. |
font |
String |
The font to use for this element. Must be one of the following strings: “default” - Default font “dialog” - Dialog box font “palette” - Palette (small) Font |
bold |
Boolean |
Specify if the font is bold. |
italic |
Boolean |
Specify if the font is italic. |
alignment |
String |
Sets the alignment for this element. Must be one of the following values: “align_left”: Left aligned “align_center”: Center aligned “align_right”: Right aligned “align_top”: Top aligned “align_fill”: Align to fill the parent’s width; may widen objects. “align_distribute”: Distribute the contents over the parent’s width. “align_row”: Distribute the contents over the parent’s width with a consistent baseline. “align_offscreen”: Align items one on top of another. |
align_children |
String |
Sets the alignment for all descendants. Possible values are the same as for alignment. |
elements |
Array |
An array of object literals that describe the subelements of this dialog box element. Its properties are the same as those described in this table. |
Some of the element types have additional attributes, as listed below.
Element type |
Property |
Type |
Description |
---|---|---|---|
static_text |
multiline |
Boolean |
If true, this static text element is multiline. Note:For Mac OS, the height property must be at least 49 to display the up/down buttons, which allow users to read the whole box content. |
edit_text |
multiline |
Boolean |
If true, this edit text element is multiline. |
|
readonly |
Boolean |
If true, this text element is read only. Note:This property is ignored when password is set to true. |
|
password |
Boolean |
If true, this text element is a password field. |
|
PopupEdit |
Boolean |
If true, it is a pop-up edit text element. |
|
SpinEdit |
Boolean |
If true, it is a spin edit text element. |
radio |
group_id |
String |
The group name to which this radio button belongs. |
ok, ok_cancel, |
ok_name |
String |
The name for the OK button. |
|
cancel_name |
String |
The name for the cancel button. |
|
other_name |
String |
The name for the other button. |
The following dialog box descriptor can be a document-level or folder-level JavaScript. The dialog box created contains text fields for your first and last name. When the OK button is clicked, the names entered are reported to the console.
var dialog1 = {
initialize: function (dialog) {
// Create a static text containing the current date.
var todayDate = dialog.store()["date"];
todayDate = "Date: " + util.printd("mmmm dd, yyyy", new Date());
dialog.load({ "date": todayDate });
},
commit:function (dialog) { // called when OK pressed
var results = dialog.store();
// Now do something with the data collected, for example,
console.println("Your name is " + results["fnam"]
+ " " + results["lnam"] );
},
description:
{
name: "Personal Data", // Dialog box title
align_children: "align_left",
width: 350,
height: 200,
elements:
[
{
type: "cluster",
name: "Your Name",
align_children: "align_left",
elements:
[
{
type: "view",
align_children: "align_row",
elements:
[
{
type: "static_text",
name: "First Name: "
},
{
item_id: "fnam",
type: "edit_text",
alignment: "align_fill",
width: 300,
height: 20
}
]
},
{
type: "view",
align_children: "align_row",
elements:
[
{
type: "static_text",
name: "Last Name: "
},
{
item_id: "lnam",
type: "edit_text",
alignment: "align_fill",
width: 300,
height: 20
}
]
},
{
type: "static_text",
name: "Date: ",
char_width: 25,
item_id: "date"
},
]
},
{
alignment: "align_right",
type: "ok_cancel",
ok_name: "Ok",
cancel_name: "Cancel"
}
]
}
};
Now, the following line can be executed from actions such as the mouse-up action of a button or a menu action.
app.execDialog(dialog1);
The following example uses a check box and a radio button field. This code might be a document-level JavaScript.
var dialog2 =
{
initialize: function(dialog) {
// Set a default value for radio button field
dialog.load({"rd01": true });
this.hasPet = false;
// Disable radio button field
dialog.enable({
"rd01" : this.hasPet,
"rd02" : this.hasPet,
"rd03" : this.hasPet
});
},
commit: function(dialog) {
// When the user presses "Ok", this handler will execute first
console.println("commit");
var results = dialog.store();
// Do something with the data, for example,
var hasPet = (this.hasPet) ? "have" : "don't have";
console.println("You " + hasPet + " a pet.");
if (this.hasPet)
console.println("You have " + this.getNumPets(results)
+ " pet(s).");
},
getNumPets: function (results) {
for ( var i=1; i<=3; i++) {
if ( results["rd0"+i] ) {
switch (i) {
case 1:
var nPets = "one";
break;
case 2:
var nPets = "two";
break;
case 3:
var nPets = "three or more";
}
}
};
return nPets;
},
ok: function(dialog) {
// The handler for the Ok button will be handed after commit
console.println("Ok!");
},
ckbx: function (dialog) {
// Process the checkbox, if the user has a pet, turn on radios
this.hasPet = !this.hasPet;
dialog.enable({
"rd01" : this.hasPet,
"rd02" : this.hasPet,
"rd03" : this.hasPet
});
},
cancel: function(dialog) { // Handle the cancel button
console.println("Cancel!");
},
other: function(dialog){ // Handle the other button
app.alert("Thanks for pressing me!");
dialog.end("other"); // End the dialog box, return "other"!
},
// The dialog box description
description:
{
name: "More Personal Information",
elements:
[
{
type: "view",
align_children: "align_left",
elements:
[
{
name: "Personal Information",
bold: true,
font: "dialog",
char_width: 30,
height: 20
},
{
type: "check_box",
item_id: "ckbx",
name: "Pet Owner"
},
{
type: "view",
align_children: "align_row",
elements:
[
{
type: "static_text",
name: "Number of pets: "
},
{
type: "radio",
item_id: "rd01",
group_id: "rado",
name: "One"
},
{
type: "radio",
item_id: "rd02",
group_id: "rado",
name: "Two",
},
{
type: "radio",
item_id: "rd03",
group_id: "rado",
name: "Three or more",
}
]
}
]
},
{
type: "gap", //Add a small vertical gap between
height: 10 //..radio fields and buttons
},
{
type: "ok_cancel_other",
ok_name: "Ok",
cancel_name: "Cancel",
other_name: "Press Me"
}
]
}
};
The following line can be executed in situations such as the mouse-up action of a button or a menu action.
var retn = app.execDialog(dialog2);
The value of retn is “ok” if the Ok button was clicked, “cancel” if the Cancel button was clicked, and “other” if the button labeled “Press Me” was clicked.
This example uses a list box.
var dialog3 = {
// This dialog box is called when the dialog box is created
initialize: function(dialog) {
this.loadDefaults(dialog);
},
// This dialog box is called when the OK button is clicked.
commit: function(dialog) {
// See the Dialog object for a description of how dialog.load
// and dialog.store work.
var elements = dialog.store()["subl"];
// do something with the data.
},
// Callback for when the button "butn" is clicked.
butn: function(dialog) {
var elements = dialog.store()["subl"]
for(var i in elements) {
if ( elements[i] > 0 ) {
app.alert("You chose \"" + i
+ "\", which has a value of " + elements[i] );
}
}
},
loadDefaults: function (dialog) {
dialog.load({
subl:
{
"Acrobat Professional": +1,
"Acrobat Standard": -2,
"Adobe Reader": -3
}
})
},
// The dialog box description
description:
{
name: "Adobe Acrobat Products", // Title of the dialog box
elements: // Child element array
[
{
type: "view",
align_children: "align_left",
elements: // Child element array
[
{
type: "cluster",
name: "Select",
elements: // Child Element Array
[
{
type: "static_text",
name: "Select Acrobat you use",
font: "default"
},
{
type: "list_box",
item_id: "subl",
width: 200,
height: 60
},
{
type: "button",
item_id: "butn",
name: "Press Me"
}
]
},
{
type: "ok_cancel"
}
]
}
]
}
}
Then execute
app.execDialog(dialog3);
In the example above, if the line type: "list_box" is replaced by type: "popup" and the height specification is removed, the example will run with a pop-up control rather than a list box.
This example shows a hierarchical list box. After the dialog box is opened, a hierarchical list is presented. After a selection is made and the user clicks the Select button, the document jumps to the destination chosen by the user. The Doc object is passed to the dialog box by making it a property of the dialog box.
var dialog4 = {
initialize: function(dialog) {
dialog.load({
subl:
{
"Chapter 1":
{
"Section 1":
{
"SubSection 1": -1,
"SubSection 2": -2,
},
"Section 2":
{
"SubSection 1": -3,
"SubSection 2": -4,
}
},
"Chapter 3": -5,
"Chapter 4": -6
}
})
},
subl: function(dialog) {
console.println("Selection Box Hit");
},
getHierChoice: function (e)
{
if (typeof e == "object") {
for ( var i in e ) {
if ( typeof e[i] == "object" ) {
var retn = this.getHierChoice(e[i]);
if ( retn ) {
retn.label = i + ", " + retn.label;
return retn;
}
// if e[i] > 0, we’ve found the selected item
} else if ( e[i] > 0 ) return { label:i, value: e[i] };
}
} else {
if ( e[i] > 0 ) return e[i];
}
},
butn: function (dialog)
{
var element = dialog.store()["subl"]
var retn = this.getHierChoice(element);
if ( retn ) {
// Write to the console the full name of the item selected
console.println("The selection you've chosen is \""
+ retn.label + "\", its value is " + retn.value );
dialog.end("ok");
// this.doc is the doc object of this document
this.doc.gotoNamedDest("dest"+retn.value);
}
else app.alert("Please make a selection, or cancel");
},
cncl: function (dialog) { dialog.end("cancel") },
// Dialog box description
description:
{
name: "My Novel",
elements:
[
{
type: "view",
align_children: "align_left",
elements:
[
{
type: "cluster",
name: "Book Headings",
elements:
[
{
type: "static_text",
name: "Make a selection",
},
{
type: "hier_list_box",
item_id: "subl",
char_width: 20,
height: 200
}
]
},
{
type: "view",
align_children: "align_row",
elements:
[
{
type: "button",
item_id: "cncl",
name: "Cancel"
},
{
item_id: "butn",
type: "button",
name: "Select"
}
]
}
]
}
]
}
};
This function attaches the Doc object to the dialog box, then passes the dialog box to the app.execDialog method. The dialog4 object and this function can be at the document level.
function dotheDialog(dialog,doc)
{
dialog.doc = doc;
var retn = app.execDialog( dialog )
}
Finally, the following script can be executed from a mouse-up action, for example.
dotheDialog( dialog4, this );
See Example 2 following trustPropagatorFunction which shows how to execute privileged code from a non-privileged context.
Executes the specified menu item.
Beginning with
Note:(
app.execMenuItem("SaveAs");
If the user preferences are set to “Save As Optimizes for Fast Web View”, a form object will not survive a Save As operation. Field objects are no longer valid, and an exception may be thrown when trying to access a Field object immediately after saving. See the examples that follow.
For security reasons, scripts are not allowed to execute the Quit menu item. Beginning with
(
To see the list of safe menus, create a form button, and in the Button Properties dialog box, select the Actions tab. From the Select Action list, select “Execute a menu item”. Finally, click the Add button to see the Menu Item dialog box with the list of safe menus.
The app.execMenuItem method may be executed, without restriction, in a privileged context, such as in the console or in a batch sequence. For folder JavaScript, app.execMenuItem can be executed, again, without restriction, through a trusted function with raised privilege. See Example 4, below.
Another approach to executing app.execMenuItem without restriction is through Sign & Certify. When the document author signs and certifies the document, privileged methods can be executed from a non-privileged context provided the document consumer lists the author’s certificate in the list of trusted identities and the consumer trusts the author for execution of embedded high privilege JavaScript.
To ensure a secure environment, the menu items that can be executed are limited to the following:
AcroSendMail:SendMail |
HandMenuItem |
ShowHideToolbarBasicTools |
ActualSize |
HelpReader |
ShowHideToolbarCommenting |
AddFileAttachment |
InsertPages |
ShowHideToolbarData |
Annots:Tool:InkMenuItem |
LastPage |
ShowHideToolbarEdit |
BookmarkShowLocation |
NextPage |
ShowHideToolbarEditing |
Close |
OneColumn |
ShowHideToolbarFile |
CropPages |
OpenOrganizer |
ShowHideToolbarFind |
DeletePages |
PageSetup |
ShowHideToolbarForms |
DocHelpUserGuide |
PrevPage |
ShowHideToolbarMeasuring |
ExtractPages |
|
ShowHideToolbarNavigation |
Find |
PropertyToolbar |
ShowHideToolbarPageDisplay |
FindCurrentBookmark |
Quit |
ShowHideToolbarPrintProduction |
FindSearch |
ReplacePages |
ShowHideToolbarRedaction |
FirstPage |
RotatePages |
ShowHideToolbarTasks |
FitHeight |
SaveAs |
ShowHideToolbarTypewriter |
FitPage |
Scan |
SinglePage |
FitVisible |
ShowHideAnnotManager |
Spelling |
FitWidth |
ShowHideArticles |
Spelling:Check |
FullScreen |
ShowHideBookmarks |
TwoColumns |
GeneralInfo (Properties) |
ShowHideFields |
TwoPages |
GeneralPrefs |
ShowHideFileAttachment |
Web2PDF:OpenURL |
GoBack |
ShowHideModelTree |
ZoomDragMenuItem |
GoBackDoc |
ShowHideOptCont |
ZoomTo |
GoForward |
ShowHideSignatures |
ZoomViewIn |
GoForwardDoc |
ShowHideThumbnails |
ZoomViewOut |
GoToPage |
|
|
This list applies only to document-level access to menu items. It does not apply to application-level JavaScript or JavaScript from a privileged context.
The list is written to the Acrobat registry and can be edited if you determine that the list must be expanded. If you need to modify the list, you can edit the related registry entries:
The key for the default list is HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Adobe\Adobe Acrobat\9.0\FeatureLockDown\cDefaultExecMenuItems.
The key for the list used by Tuner is HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Adobe\Adobe Acrobat\9.0\FeatureLockDown\cAdminExecMenuItems.
For both keys, the value name is tWhiteList and the type is REG_SZ. The value data contains all menu item names and each menu item name is separated with the "|" delimiter.
See also addMenuItem, addSubMenu, and hideMenuItem. Use listMenuItems to have the console list the names of all menu items.
cMenuItem |
The menu item to execute. A list of menu item names can be obtained with listMenuItems. |
oDoc |
(optional, |
This example executes the File > Open menu item. It displays a dialog box asking for the file to be opened.
app.execMenuItem("Open");
This example illustrates how a form object does not survive the execution of app.execMenuItem("SaveAs"), as noted above.
var f = this.getField("myField");
// Assume preferences set to save linearized
app.execMenuItem("SaveAs");
// Exception thrown, field not updated
f.value = 3;
After executing app.execMenuItem("SaveAs"), Field objects must be acquired again.
var f = this.getField("myField");
// Assume preferences set to save linearized
app.execMenuItem("SaveAs");
// Get the field again after the linear save
var f = getField("myField");
// Field updated to a value of 3
f.value = 3;
Execute app.execMenuItem in folder JavaScript using a trusted function.
myTrustedMenu = app.trustedFunction( function( name )
{
app.beginPriv();
app.execMenuItem(name);
app.endPriv();
});
Once
myTrustedMenu("PropertyToolbar");
may be executed from a non-privileged context, such as a mouse-up button action, without silent failure. The script above shows/hides the Properties toolbar.
Note:This method has been superseded by the plugIns property.
Obtains the name of the nth plug-in that has been loaded by the viewer.
nIndex |
The nth plug-in loaded by the viewer. |
cName, the plug-in name that corresponds to nIndex.
Returns the path to folders created during installation. A distinction is made between application folders and user folders. The method throws a GeneralError exception (see Error object) if the path does not exist.
Note:(
(optional) The category of folder sought. Valid values are app (the default) and user. |
|
cFolder |
(optional) A platform-independent string that indicates the folder. Valid values are root, eBooks, preferences, sequences, documents, The default is root. |
The path to the folder determined by the parameters. An exception is thrown if the folder does not exist.
Find the path to the user’s Sequences folder.
try {
var userBatch = app.getPath("user","sequences");
} catch(e) {
var userBatch = "User has not defined any custom batch sequences";
}
console.println(userBatch);
On a Windows platform, create and save a document to the My Documents folder.
var myDoc = app.newDoc();
var myPath = app.getPath("user", "documents") + "/myDoc.pdf"
myDoc.saveAs(myPath);
myDoc.closeDoc();
3.01 |
|
|
|
Goes to the previous view on the view stack, which is equivalent to clicking the Previous View button on the
Create a go-back button. This code could be part of a batch sequence, for example, to place navigation buttons on the selected PDF documents.
var aRect = this.getPageBox();
var width = aRect[2] - aRect[0];
// The rectangle is 12 points high and 18 points wide, centered at bottom
rect = [width/2-8, 10, width/2+8, 22];
f = this.addField("goBack", "button", 0, rect);
f.textFont="Wingdings";
f.textSize=0;
f.buttonSetCaption("\u00E7"); // Left pointing arrow
f.setAction("MouseUp", "app.goBack()"); // Add an action
3.01 |
|
|
|
Goes to the next view on the view stack, which is equivalent to clicking the go Next View button on the
See the example following app.goBack.
Removes a specified menu item.
See also addMenuItem, addSubMenu, execMenuItem, and listMenuItems.
Note:This method can only be executed during a console or application initialization event. See the event object for a discussion of JavaScript events.
cName |
The menu item name to remove. Menu item names can be discovered with listMenuItems. |
Removes the specified toolbar button from the “Add-on” toolbar of Acrobat 9 or earlier. In Acrobat X, hides the specified button from the Plugin Addon Tools panel on the right side of the display area.
Note:This method can only be executed during console or application initialization event. See the event object for a discussion of JavaScript events.
cName |
The name of the toolbar button to remove. Toolbar item names can be discovered with listToolbarButtons. |
A file named, myConfig.js, containing the following script is placed in one of the folder-level JavaScript folders.
app.hideToolbarButton("Hand");
When the viewer is started, the “Hand” icon does not appear.
Launches a URL in a browser window.
Note:Beginning with Acrobat 8.1, File and JavaScript URLs can be executed only when operating in a privileged context, such as during a batch or console event. File and JavaScript URLs begin with the scheme names javascript or file.
cURL |
A string that specifies the URL to launch. |
bNewFrame |
(optional) If true, this method launches the URL in a new window of the browser application. The default is false. |
The value undefined is returned on success. An exception is thrown on failure.
app.launchURL("http://www.example.com/", true);
Add an online help item to the menu system. This code should be placed in a folder-level JavaScript file, or executed from the JavaScript Debugger console.
app.addMenuItem({
cName: "myHelp", cUser: "Online myHelp",
cParent: "Help",
cExec: "app.launchURL('www.example.com/myhelp.html');",
nPos: 0
});
Related methods are openDoc and the Doc object getURL method.
5.0 |
|
|
|
Beginning with
Prior to
See also addMenuItem, addSubMenu, execMenuItem, and hideMenuItem.
Array of TreeItem objects.
A generic JavaScript object that represents a menu or toolbar item hierarchy. An array of these objects is returned by app.listMenuItems and app.listToolbarButtons (starting in
cName |
The name of a menu item or toolbar button. |
oChildren |
(optional) An array of treeItem objects containing the submenus or flyout buttons. |
List all menu item names to the console.
var menuItems = app.listMenuItems()
for( var i in menuItems)
console.println(menuItems[i] + "\n")
List all menu items to the console using a fancy format.
function FancyMenuList(m, nLevel)
{
var s = "";
for (var i = 0; i < nLevel; i++) s += " ";
console.println(s + "+-" + m.cName);
if ( m.oChildren != null )
for ( var i = 0; i < m.oChildren.length; i++ )
FancyMenuList(m.oChildren[i], nLevel + 1);
}
var m = app.listMenuItems();
for ( var i=0; i < m.length; i++ ) FancyMenuList(m[i], 0);
5.0 |
|
|
|
Beginning with
Prior to
(
Array of TreeItem objects
List all toolbar names in the console.
var toolbarItems = app.listToolbarButtons()
for( var i in toolbarItems)
console.println(toolbarItems[i] + "\n")
See also the hideToolbarButton method.
9.0 |
|
|
|
Specifies a cross-domain policy file from a location specified by the url parameter. Acrobat uses policy files as a permission mechanism to permit PDFs to load data from servers other than their own. With the addition of app.loadPolicyFile(), Acrobat can load policy files from arbitrary locations, as shown in the following example:
app.loadPolicyFile("http://www.example.com/sub/dir/pf.xml");
This causes Acrobat to retrieve a policy file from the specified URL when a crossdomain policy check is required. Any permissions granted by the policy file at that location will apply to all content at the same level or lower in the virtual directory hierarchy of the server. The following code continues the previous example:
this.getURL("http://www.example.com/sub/dir/vars.txt", true) // allowed
this.getURL("http://www.example.com/sub/dir/deep/vars2.txt", true) // allowed
this.getURL("http://www.example.com/mydir/vars3.txt", true) // not allowed
Any number of policy files can be loaded using loadPolicyFile(). When considering a request that requires a policy file, Acrobat always waits for the completion of any policy file downloads before denying a request. As a final fallback, if no policy file specified with loadPolicyFile() authorizes a request, Acrobat consults the original default location, /crossdomain.xml.
url |
The url of the location of a cross-domain policy file. The length of url is limited to 1024 bytes . If a larger string is passed an exception is thrown. Note:This method does not take single object argument with properties that contain the arguments as many JavaScript for Acrobat methods do. The argument of this method is a string. |
Nothing
Note:This method is a Windows-only feature.
Displays an address book dialog box to let the user choose e-mail recipients. The dialog box is optionally prepopulated with semicolon-separated lists of addressees in the cTo, cCc, and cBcc strings. The bCc and bBcc Boolean values control whether the user should be allowed to choose CC and BCC recipients.
See also mailMsg, the Doc object methods mailDoc and mailForm, the FDF object mail method and the Report object mail method.
Note:(
cTo |
(optional) A semicolon-separated list of “To” addressees to use. |
cCc |
(optional) A semicolon-separated list of CC addressees to use. |
cBcc |
(optional) A semicolon-separated list of BCC addressees to use. |
cCaption |
(optional) A string to appear on the caption bar of the address dialog box. |
bCc |
(optional) A Boolean value to indicate whether the user can choose CC recipients. |
bBcc |
(optional) A Boolean value to indicate whether the user can choose BCC recipients. This Boolean should only be used when bCc is true; otherwise, the method fails (and returns undefined). |
On failure (the user cancelled), returns undefined. On success, returns an array of three strings for To, CC, and BCC.
Give the user two chances to provide mail addresses.
var attempts = 2;
while (attempts > 0)
{
var recipients = app.mailGetAddrs
({
cCaption: "Select Recipients, Please",
bBcc: false
})
if (typeof recipients == "undefined" ) {
if (--attempts == 1)
app.alert("You did not choose any recipients, try again");
} else break;
}
if (attempts == 0)
app.alert("Cancelling the mail message");
else {
// JavaScript statements to send mail
}
Sends out an e-mail message with or without user interaction.
See also the Doc object mailDoc and mailForm methods, the FDF object mail method and the Report object mail method.
Note:On Windows: The client machine must have its default mail program configured to be MAPI enabled to use this method.
bUI |
Indicates whether user interaction is required. If true, the remaining parameters are used to seed the compose-new-message window that is displayed to the user. If false, the cTo parameter is required and others are optional. Note:( |
cTo |
A semicolon-separated list of addressees. |
cCc |
(optional) A semicolon-separated list of CC addressees. |
cBcc |
(optional) A semicolon-separated list of BCC addressees. |
cSubject |
(optional) Subject line text. The length limit is 64 KB. |
cMsg |
(optional) Mail message text. The length limit is 64 KB. |
Open the compose new message window.
app.mailMsg(true);
Send the message to fun1@example.com and fun2@example.com.
app.mailMsg(false, "fun1@example.com; fun2@example.com", "", "",
"This is the subject", "This is the body of the mail.");
It is possible to compose a message containing form data.
var cMyMsg = "Below are the current budget figures:\n\n";
cMyMsg += "Date Compiled: " + this.getField("date").value + "\n";
cMyMsg += "Current Estimate: " + this.getField("budget").value + "\n";
app.mailMsg({
bUI: true,
cTo: "myBoss@example.com",
cSubject: "The latest budget figures",
cMsg: cMyMsg
} );
Creates a new document and returns its Doc object. The optional parameters specify the media box dimensions of the document in points.
Note:This method can only be executed during a batch or console event. See Privileged versus non-privileged context. See the event object for a discussion of JavaScript events.
nWidth |
(optional) The width (in points) for the new document. The default value is 612. |
nHeight |
(optional) The height (in points) for the new document. The default value is 792. |
The object of the newly created document.
Add a New item to the
app.addSubMenu({ cName: "New", cParent: "File", nPos: 0 })
app.addMenuItem({ cName: "Letter", cParent: "New", cExec:
"app.newDoc();"});
app.addMenuItem({ cName: "A4", cParent: "New", cExec:
"app.newDoc(420,595)"});
app.addMenuItem({ cName: "Custom...", cParent: "New", cExec:
"var nWidth = app.response({ cQuestion:'Enter Width in Points',\
cTitle: 'Custom Page Size'});"
+"if (nWidth == null) nWidth = 612;"
+"var nHeight = app.response({ cQuestion:'Enter Height in Points',\
cTitle: 'Custom Page Size'});"
+"if (nHeight == null) nHeight = 792;"
+"app.newDoc({ nWidth: nWidth, nHeight: nHeight })"});
The script above works for versions of
If this item is not checked, the app.newDoc method must be executed through a trustedFunction because execution of JavaScript through a menu event is no longer privileged beginning with
The same example can be worked as follows:
trustedNewDoc = app.trustedFunction( function (nWidth, nHeight)
{
app.beginPriv();
switch( arguments.length ) {
case 2:
app.newDoc( nWidth, nHeight );
break;
case 1:
app.newDoc( nWidth );
break;
default:
app.newDoc();
}
app.endPriv();
})
app.addSubMenu({ cName: "New", cParent: "File", nPos: 0 })
app.addMenuItem({ cName: "Letter", cParent: "New", cExec:
"trustedNewDoc();"});
app.addMenuItem({ cName: "A4", cParent: "New", cExec:
"trustedNewDoc(420,595)"});
app.addMenuItem({ cName: "Custom...", cParent: "New", cExec:
"var nWidth = app.response({ cQuestion:'Enter Width in Points',\
cTitle: 'Custom Page Size'});"
+"if (nWidth == null) nWidth = 612;"
+"var nHeight = app.response({ cQuestion:'Enter Height in Points',\
cTitle: 'Custom Page Size'});"
+"if (nHeight == null) nHeight = 792;"
+"trustedNewDoc(nWidth, nHeight) "});
The code is incomplete. In the case of the Custom menu item, additional lines can be inserted to prevent the user from entering the empty string, or a value too small or too large. See the
Create a blank document and acquire the Doc object, then insert a watermark.
var myNewDoc = app.newDoc();
myNewDoc.addWatermarkFromText("Confidential",0,font.Helv,24,color.red);
This example uses the Doc object addWatermarkFromText method.
Creates a new collection-based PDF, a PDF portfolio, with no content.
To work with an existent PDF portfolio, begin with Doc.collection.
A Doc object of the newly created PDF.
Create a new PDF portfolio and get the Doc object of the newly created PDF.
var doc = app.newCollection();
Creates a new FDF object that contains no data.
Note:This method is available only during batch, console and application initialization. Not available in
A new FDF object.
Create an FDF with an embedded PDF file.
var fdf = app.newFDF();
fdf.addEmbeddedFile( "/c/myPDFs/myFile.pdf", 1);
fdf.save( "/c/myFDFs/myFile.fdf" );
This example continues following the description of app.openFDF.
5.0 |
|
|
|
Opens a specified PDF document and returns its Doc object. This object can be used by the script to call methods, or to get or set properties in the newly opened document.
Note:When a batch sequence is running, a modal dialog box is open, which prevents user interference while processing. Consequently, this method cannot be executed through a batch sequence.
Note:The app.openDoc API cannot be called from a doc open script. A script which is executed on the doc open action is known as doc open script. In such cases, Viewer raises a NotAllowedError exception, which escript passes to the user. However, it can be called successfully from other triggers, such as a page open action.
An exception is thrown and an invalid Doc object is returned when an HTML document is opened using this method. To catch the exception, enclose app.openDoc in a try/catch construct. See Example 2 below.
cPath |
A device-independent path to the document to be opened. If oDoc is specified, the path can be relative to it. The target document must be accessible in the default file system. Note:When cFS is set to “CHTTP”, the cPath string should be escaped, perhaps using the core JavaScript global function encodeURI. See Example 5 (Acrobat 7.0) below. |
oDoc |
(optional) A Doc object to use as a base to resolve a relative cPath. Must be accessible in the default file system. |
cFS |
(optional, |
bHidden |
(optional, |
bUseConv |
(optional, Note:( |
cDest |
(optional, |
A Doc object or null:
In
In
Beginning with the
During a batch, console or menu event, openDoc ignores the disclosed property and returns the Doc object of the file specified by cPath.
During any other event, openDoc returns the Doc, if disclosed is true, and null, otherwise.
This example opens another document, inserts a prompting message into a text field, sets the focus in the field, and then closes the current document.
var otherDoc = app.openDoc("/c/temp/myDoc.pdf");
otherDoc.getField("name").value="Enter your name here: "
otherDoc.getField("name").setFocus();
this.closeDoc();
Same example as above, but a relative path is used.
var otherDoc = app.openDoc("myDoc.pdf", this);
otherDoc.getField("name").value="Enter your name here: "
otherDoc.getField("name").setFocus();
this.closeDoc();
This example uses the Doc closeDoc method and the Field object setFocus method.
Open an HTML document on the user’s hard drive and convert it to PDF.
try {
app.openDoc("/c/myWeb/myHomePage.html");
} catch (e) {};
Open a hidden PDF document, extract information from it, and close it.
oDoc = app.openDoc({
cPath:"/C/myDocs/myInfo.pdf",
bHidden: true
});
var v = oDoc.getField("myTextField").value;
this.getField("yourTextField").value = v;
oDoc.closeDoc();
Open a non-PDF file by converting it to a PDF document. The following script can be executed successfully from the console.
app.openDoc({
cPath: "/c/temp/myPic.jpg",
bUseConv: true
})
Open a file from a WebDAV server. The app.openDoc method requires the path to the file to be escaped.
var myURL = encodeURI("http://www.example.com/My Folder/ComDoc.pdf");
app.openDoc({cPath: myURL, cFS: "CHTTP" });
See also app.browseForDoc.
Open a document and jump to a named destination.
app.openDoc({ cPath: "/c/temp/myDoc.pdf", cDest: "myDest" });
In versions previous to 8.0, this jump is not possible unless the document is disclosed. See the example following gotoNamedDest.
Creates a new FDF object by opening the specified file. The FDF object has methods and properties that can be used on the data that this file contains.
Note:This method is available only during batch, console and application initialization events. See also Privileged versus non-privileged context.
cDIPath |
The device-independent path to the file to be opened. |
The FDF object for the FDF file that is opened.
Create an FDF file with an embedded PDF file.
var fdf = app.newFDF();
fdf.addEmbeddedFile( "/c/myPDFs/myFile.pdf", 1);
fdf.save( "/c/myFDFs/myFile.fdf" ); // save and close this FDF
// Now open the FDF file and embed another PDF doc.
var fdf = app.openFDF( "/c/myFDFs/myFile.fdf" );
fdf.addEmbeddedFile( "/c/myPDFs/myOtherFile.pdf", 1);
fdf.save( "/c/myFDFs/myFile.fdf" ); // save and close this FDF
See the FDF object signatureSign method for another example of usage.
5.0 |
|
|
|
Note:popUpMenuEx is preferred over this method.
Creates a pop-up menu at the current mouse position, containing the specified items.
cItem |
(optional) If the argument is a string, it is listed in the menu as a menu item. The menu item name "-" is reserved to draw a separator line in the menu. |
Array |
(optional) If the argument is an array, it appears as a submenu where the first element in the array is the parent menu item. This array can contain further submenus. |
The name of the menu item that was selected, or null if no item was selected.
Create a pop-up menu consisting of chapter of a document.
var cChoice = app.popUpMenu("Introduction", "-", "Chapter 1",
[ "Chapter 2", "Chapter 2 Start", "Chapter 2 Middle",
["Chapter 2 End", "The End"]]);
app.alert("You chose the \"" + cChoice + "\" menu item");
6.0 |
|
|
|
Creates a pop-up menu at the current mouse position. Each of the parameters is a MenuItem object that describes a menu item to be included in the pop-up menu.
This method is preferred over the use of popUpMenu.
One or more MenuItem objects (see below).
The cReturn value of the menu item that was selected, or its cName if cReturn was not specified for that item. The method returns null if no selection was made.
This generic JavaScript object represents a menu item. It has the following properties.
Property |
Description |
---|---|
cName |
The menu item name, which is the string to appear on the menu item. The value of "-" is reserved to draw a separator line in the menu. |
bMarked |
(optional) A Boolean value specifying whether the item is to be marked with a check. The default is false (not marked). |
bEnabled |
(optional) A Boolean value specifying whether the item is to appear enabled or grayed out. The default is true (enabled). |
cReturn |
(optional) A string to be returned when the menu item is selected. The default is the value of cName. |
oSubMenu |
(optional) A MenuItem object representing a submenu item or an array of submenu items, each represented by a MenuItem object. |
Show all the features of the popUpMenuEx method.
var cChoice = app.popUpMenuEx
(
{cName: "Item 1", bMarked:true, bEnabled:false},
{cName: "-"},
{cName: "Item 2", oSubMenu:
[ {cName: "Item 2, Submenu 1"},
{
cName: "Item 2, Submenu 2",
oSubMenu: {cName:"Item 2, Submenu 2, Subsubmenu 1", cReturn: "0"}
}
]
},
{cName: "Item 3"},
{cName: "Item 4", bMarked:true, cReturn: "1"}
)
app.alert("You chose the \"" + cChoice + "\" menu item");
Because the popupMenuEx method takes a list of MenuItem objects, its parameters cannot be passed to it as a JavaScript variable. As a workaround, you can create an array of menu items and use the Function object method apply from core JavaScript. This method allows arguments to be passed as an array.
// Declare pop-up menu properties as an array.
var aParams = [
{cName: "Example Web Page", cReturn: "www.example.com"},
{cName: "-"},
{cName: "The Example Product Line",
cReturn: "www.example.com/products/main.html"},
{cName: "Example Reader",
cReturn: "www.example.com/products/reader/main.html"}
];
// Apply the function app.popUpMenuEx to the app object, with an array
// of parameters aParams
var cChoice = app.popUpMenuEx.apply( app, aParams );
if ( cChoice != null ) app.launchURL(cChoice);
6.0 |
|
|
|
Removes a previously added button from the toolbar.
Note:(
If no document was open in
Similarly, if a certain document was the active document when a toolbutton was added, that same document must be active for the button to be removed using removeToolButton.
In the case of a document that is active when the toolbutton is added, the button is automatically removed when this document is closed. See also the notes following the description of addToolButton.
cName |
The language-independent identifier provided when addToolButton was called. |
See the example following addToolButton.
This example shows the removal of a toolbutton with the same context as addToolButton. Initially, there is no document open in the
app.addToolButton({cName: "button1", cExec:"app.alert('pressed');",
cTooltext:"Button1"});
Open a PDF document in
app.removeToolButton({cName:"button1"});
An exception is thrown and the removal of the button fails.
If you close the PDF document and execute the removeToolButton script again, the button is removed.
3.01 |
|
|
|
Displays a dialog box containing a question and an entry field for the user to reply to the question.
The question to be posed to the user. |
|
cTitle |
(optional) The title of the dialog box. |
cDefault |
(optional) A default value for the answer to the question. If not specified, no default value is presented. |
bPassword |
(optional) If true, indicates that the user’s response should show as asterisks (*) or bullets (•) to mask the response, which might be sensitive information. The default is false. |
cLabel |
(optional, |
A string containing the user’s response. If the user clicks the Cancel button, the response is the null object.
Asks for a response from the user and report back the response.
var cResponse = app.response({
cQuestion: "How are you today?",
cTitle: "Your Health Status",
cDefault: "Fine",
cLabel: "Response:"
});
if (cResponse == null)
app.alert("Thanks for trying anyway.");
else
app.alert("You responded, \""+cResponse+"\", to the health "
+ "question.",3);
5.0 |
|
|
|
Specifies a JavaScript script and a time period. The script is executed every time the period elapses.
The return value of this method must be held in a JavaScript variable. Otherwise, the interval object is subject to garbage-collection, which would cause the clock to stop.
To terminate the periodic execution, pass the returned interval object to clearInterval.
Note:Beginning with
Opening and closing the document JavaScripts dialog box causes the JavaScript interpreter to re-read the document JavaScripts and consequently to re-initialize any document-level variables. Resetting document-level variables in this way after JavaScript expressions have been registered to be evaluated by setInterval or setTimeOut may cause JavaScript errors if those scripts use document-level variables.
See also clearInterval, setTimeOut and clearTimeOut.
cExpr |
The JavaScript script to be executed. |
nMilliseconds |
The time period in milliseconds. |
An interval object
Create a simple color animation on a field called “Color” that changes every second.
function DoIt() {
var f = this.getField("Color");
var nColor = (timeout.count++ % 10 / 10);
// Various shades of red.
var aColor = new Array("RGB", nColor, 0, 0);
f.fillColor = aColor;
}
// save return value as a variable
timeout = app.setInterval("DoIt()", 1000);
// Add a property to our timeout object so that DoIt() can keep
// a count going.
timeout.count = 0;
See setTimeOut for an additional example.
5.0 |
|
|
|
Specifies a JavaScript script and a time period. The script is executed one time only, after the period elapses.
The return value of this method must be held in a JavaScript variable. Otherwise, the timeout object is subject to garbage-collection, which would cause the clock to stop.
To cancel the timeout event, pass the returned timeout object to clearTimeOut.
Note:Beginning with
Opening and closing the document JavaScripts dialog box causes the JavaScript interpreter to re-read the document JavaScripts and consequently to re-initialize any document-level variables. Resetting document-level variables in this way after JavaScript expressions have been registered to be evaluated by setInterval or setTimeOut may cause JavaScript errors if those scripts use document-level variables.
See also clearTimeOut, setInterval, and clearInterval.
cExpr |
The JavaScript script to be executed. |
nMilliseconds |
The time period in milliseconds. |
A timeout object
Create a simple running marquee. Assume there is a text field named “marquee”. The default value of this field is “Adobe
// Document-level JavaScript function
function runMarquee() {
var f = this.getField("marquee");
var cStr = f.value;
// get field value
var aStr = cStr.split(""); // Convert to an array
aStr.push(aStr.shift()); // Move first char to last
cStr = aStr.join(""); // Back to string again
f.value = cStr; // Put new value in field
}
// Insert a mouse-up action into a "Go" button
run = app.setInterval("runMarquee()", 100);
// stop after a minute
stoprun=app.setTimeOut("app.clearInterval(run)",6000);
// Insert a mouse-up action into a "Stop" button
try {
app.clearInterval(run);
app.clearTimeOut(stoprun);
} catch (e){}
The Stop button code is protected with a try/catch construct. If the user clicks the Stop button without having first clicked Go, run and stoprun will be undefined and the Stop code will throw an exception. When the exception is thrown, the catch code is executed. In this example, the code does nothing if the user clicks Stop first.
Marks a function as trusted. Trusted functions can explicitly increase the current privilege level for their stack frame. Typically, the stack frame (which corresponds to the body of the function) contains security-restricted methods that require a privileged context in which to run. By increasing the privilege level, these restricted methods can be executed in non-privileged contexts. See Privileged versus non-privileged context.
Within the body of the function definition, calls to the app.beginPriv and app.endPriv methods must enclose any code that normally executes in a privileged context, as the examples below show.
Note:This method is available only during batch, console and application initialization events
oFunc |
A function object that specifies the function to mark as trusted. |
On success, returns the same function object that was passed in. After successful execution, the function object will be trusted. On error, throws NotAllowedError.
This method can be called in two ways.
myTrustedFunction = app.trustedFunction(
function()
{
<function body>
}
);
or
function myOtherTrustedFunction()
{
<function body>
};
app.trustedFunction(myOtherTrustedFunction);
The following examples, along with the examples following the app.trustPropagatorFunction method, contain many comments that clarify the notion of trusted function and highlight some of the nuances of the topic.
app.newDoc is a security-restricted method that needs a privileged context in which to run. For example, it cannot normally be executed from a mouse-up event. This example shows how this method can be executed from a mouse-up event by creating a trusted function.
Place the following script in a .js file in the User (or App) JavaScript folder.
trustedNewDoc = app.trustedFunction( function (nWidth, nHeight)
{
// Additional code may appear above
app.beginPriv(); // Explicitly raise privilege
app.newDoc( nWidth, nHeight );
app.endPriv();
// Additional code may appear below.
})
After
trustedNewDoc( 200, 200 );
Because of security restrictions, app.newDoc(200,200) cannot normally be executed from a mouse-up event. The trusted function permits the creation of a new document.
Note:This example is simplified. The trusted function could be modified so that it also has the two optional arguments of the app.newDoc method.
The trustedNewDoc function can also be executed as a menu item.
app.addMenuItem( {
cName: "myTrustedNewDoc",
cUser: "New Doc", cParent: "Tools",
cExec: "trustedNewDoc(200,200)", nPos: 0
} );
Again, trustedNewDoc could be enhanced by having the user input the dimensions for the new document, either through a series of app.response dialog boxes, or a full dialog box, created by app.execDialog.
Note:If app.newDoc is not enclosed in the app.beginPriv/app.endPriv pair, executing trustedNewDoc from a non-privileged context will fail and an exception will be thrown. You must explicitly raise the privilege level in the way shown.
The app.activeDocs property behaves differently depending on the setting:
During a console or batch event, it returns an array of all active documents.
In a non-privileged context, it returns an array of only those active documents that have their disclosed property set to true.
To overcome this limitation in non-privileged context, you can define a trusted function that raises the privilege level and calls activeDocs. This function would be defined in a .js file in the User (or App) JavaScript folder.
trustedActiveDocs = app.trustedFunction (
function()
{
app.beginPriv(); // Explicitly raise the privilege
var d = app.activeDocs;
app.endPriv();
return d;
}
)
The following code can be executed from a mouse-up action of a form button.
var d = trustedActiveDocs();
console.println("There are d = " + d.length
+ " files open in the viewer.")
for ( var i=0; i< d.length; i++)
console.println((i+1) + ". " + d[i].documentFileName )
The console reports the number and file name of all documents—disclosed or not—open in the viewer.
A trusted function is capable of explicitly increasing the current privilege level only for its own stack frame. This example shows some related issues.
The following code attempts to make a trusted function more modular:
function mySaveAs(doc, path)
{
doc.saveAs(doc, path);
}
myFunc = app.trustedFunction( function (doc, path)
{
// privileged and/or non-privileged code here
app.beginPriv();
mySaveAs(doc, path);
app.endPriv();
// privileged and/or non-privileged code here
}
A problem occurs because when the privileged code doc.saveAs(doc, path) is executed, it is not within the stack frame (function body) of the calling trusted function myFunc but rather within the stack frame of mySaveAs, which is not a trusted function. Therefore, when myFunc is executed in a non-privileged context, it throws an exception.
A possible solution is to make mySaveAs into a trusted function so that myFunc succeeds. However, this exposes the privileged doc.saveAs function to non-privileged execution by anyone that knows this function is on your system.
You cannot simply enclose doc.saveAs(doc,path) in a beginPriv/endPriv pair. When myFunc is run from a non-privileged context, an exception will be thrown by the app.beginPriv within the body of the mySaveAs function. This is because mySaveAs is not trusted and therefore is not authorized to request an increased privilege level.
To summarize the observations above, there is a need for a kind of function that has the following characteristics:
It can be called by a trusted function.
It is not trusted itself and therefore cannot be directly called from a non-privileged context.
A trust propagator function satisfies these criteria (see trustPropagatorFunction below).
Marks a function as a trust propagator. Such a function is not itself trusted but can inherit trust if called from a trusted function.
A trust propagator function propagates trust, not privilege. Therefore, as with the method app.trustedFunction, an app.beginPriv/app.endPriv pair must enclose any code within the function body that normally executes in a privileged context.
Trust propagator functions can play the role of utility functions. They can be called by a trusted function and by another trust propagator function, but they cannot successfully be called by a function that is not trusted in a non-privileged context.
Note:Functions defined in .js files in the App JavaScript folder are implicitly trust propagator functions. Functions defined in .js files in the User JavaScript folder are not.
This method is available only during batch, console, and application initialization.
This method can be called in two ways.
myPropagatorFunction = app.trustPropagatorFunction(
function()
{
<function body>
}
);
or
function myOtherPropagatorFunction()
{
<function body>
};
app.trustPropagatorFunction(myOtherPropagatorFunction);
oFunc |
A function object that specifies the function to mark as a trust propagator. |
On success, returns the same function object that was passed in. After successful execution, the function object will be a trust propagator. On error, throws NotAllowedError.
For background, see Example 3 following trustedFunction.
This example defines a trust propagator function, mySaveAs, to save a file to a folder, and a trusted function, myTrustedSpecialTaskFunc, to perform various tasks involving privileged and non-privileged code. The mySaveAs function cannot be called directly in a non-privileged context.
mySaveAs = app.trustPropagatorFunction(function(doc,path)
{
app.beginPriv();
doc.saveAs(path);
app.endPriv();
})
myTrustedSpecialTaskFunc = app.trustedFunction(function(doc,path)
{
// Privileged and/or non-privileged code above
app.beginPriv();
mySaveAs(doc,path);
app.endPriv();
// Privileged and/or non-privileged code below
});
Executing the code from a mouse-up button, for example, saves the current document to the specified path.
myTrustedSpecialTaskFunc(this, "/c/temp/mySavedDoc.pdf");
This example develops a simple dialog box using the app.execDialog method and executes privileged code.
The dialog box asks for your name and asks you to browse for a document from your local hard drive (or a network drive). When you click the OK button, the selected file is loaded into the viewer and your name is placed in the author field of the document properties. (The insertion of the name only occurs if the author field is empty.) The dialog box also displays the value of identity.email, which is privileged information.
Any privileged code is enclosed by a beginPriv/endPriv pair.
Note the use of the ANTrustPropagateAll function, which is useful for creating dialog boxes that use privileged code. It takes a single object as its argument, turns every function in the object into a trust propagator function, then returns that object.
myDialog = app.trustedFunction(function()
{
app.beginPriv();
var dialog = ANTrustPropagateAll({
initialize:function(dialog) {
this.data = {}; // An object to hold dialog data
app.beginPriv();
dialog.load({ "emai": "Email: " + identity.email });
app.endPriv();
},
commit:function (dialog) { // Called when OK pressed
var results = dialog.store();
console.println("Your name is " + results["name"] );
this.data.name = results["name"];
},
brws: function (dialog) {
app.beginPriv();
var oRetn = app.browseForDoc();
if ( typeof oRetn != "undefined")
this.data.oRetn = oRetn;
app.endPriv();
},
doDialog:function() {
app.beginPriv();
var retn = app.execDialog(this);
app.endPriv();
return retn;
},
description: {
name: "Open File & Populate Info Field",
align_children: "align_left",
elements:
[
{
type: "view",
align_children: "align_left",
elements:
[
{
type: "view",
align_children: "align_row",
elements:
[
{
type: "static_text",
name: "Name: "
},
{
item_id: "name",
type: "edit_text",
alignment: "align_fill",
width: 300,
height: 20
},
]
},
{
type: "static_text",
item_id: "emai",
name: "Email: ",
char_width: 25
},
{
type: "gap",
height: 10
},
{
type: "view",
align_children: "align_row",
elements:
[
{
type: "button",
name: "Browse",
item_id: "brws"
},
{
type: "ok_cancel",
ok_name: "Ok",
cancel_name: "Cancel"
}
]
}
]
}
]
}
});
app.endPriv();
try { // Protect against user pressing the Esc key
// After everything is set up, run the dialog box using the doDialog
// function, defined in the object dialog.
var retn = dialog.doDialog();
app.beginPriv();
// If the user clicked the Ok button and there is oRetn data we load
// the requested file using app.openDoc(), a restricted method.
if ( (retn == "ok") && dialog.data.oRetn ) {
var oDoc = app.openDoc({
cPath: dialog.data.oRetn.cPath,
cFS: dialog.data.oRetn.cFS
});
if ( !oDoc.info.Author )
oDoc.info.Author = dialog.data.name;
}
app.endPriv();
} catch(e) {}
})
This dialog box can be activated from a button or, more appropriately, from a menu item or a toolbar button. For example, place the following code in a User JavaScript file to add a menu item to the Tools menu.
app.addMenuItem( { cName: "myDialog", cUser: "My Cool Dialog",
cParent: "Tools", cExec: "myDialog()", nPos: 0 } );