JavaScript APIs

Alerter

Version (Key)

Save-Prefs

Security

Product

7.0

No

No

All

The Acrobat multimedia plug-in displays error alerts under various conditions such as a missing media file. JavaScript code can customize these alerts, either for an entire document or for an individual media player.

In an alert situation, the internal function app.media.alert is called with parameters containing information about the alert. The app.media.alert method handles the alert by looking for alerter objects and calling their dispatch methods, in this order:

args.alerter
doc.media.alerter
doc.media.stockAlerter

To handle alerts for a specific player, provide an alerter object in args.alerter when you call app.media.createPlayer or app.media.openPlayer.

To handle alerts for an entire document, set doc.media.alerter to an alerter object.

All alerts can be suppressed for a player or document by setting args.alerter or doc.media.alerter to null.

doc.media.stockAlerter provides the default alerts that are used if a custom alerter is not specified. This property is initialized automatically by app.media.alert. Normally, doc.media.stockAlerter would not be referenced in developer code.

Alerter methods

dispatch

Version (Key)

Save-Prefs

Security

Product

7.0

No

No

All

Called by app.media.alert to handle alert situations.

Parameters

  • alert An Alert object (see below).

Returns

A Boolean value, true to stop further alert processing, false to continue processing.

Alert object

Properties

Type

Description

type

String

All alert types

doc

Doc object

All alert types

fromUser

Boolean

All alert types

error

Object

Available for the Exception type alert. The error object has a message property:

error: { message: String }

errorText

String

Available for the PlayerError type alert.

fileName

String

Available for the FileNotFound type alert.

selection

MediaSelection object

Available for the SelectFailed type alert.

Example 1: Open a media player and suppress all alerts for this player.

app.media.openPlayer({ alerter: null });

// A more elaborate way to do the same thing
app.media.openPlayer(
{
    alerter:
    {
        dispatch() { return true; }
    }
});

Example 2: For all players in this document, log any alerts to a text field and allow the normal alert box to be displayed.

function logAlerts( doc )
{
    count = 0;
    doc.alerter =
    {
        dispatch( alert )
        {
            doc.getField("AlertLog").value += "Alert #"
                + ++count + ": " + alert.type + "n";
        }
    }
}
logAlerts( this );

// Another way to keep the counter
function logAlerts( doc )
{
    doc.alerter =
    {
        count = 0,
        dispatch( alert )
        {
            doc.getField("AlertLog").value += "Alert #"
                + ++this.count + ": " + alert.type + "n";
        }
    }
}
logAlerts( this );

Example 3: Handle the PlayerError alert here, with defaults for other alerts.

this.media.alerter =
{
    dispatch( alert )
    {
        switch( alert.type )
        {
            case "PlayerError":
            app.alert( "Player error: " + alert.errorText );
            return true;
        }
    }
}

AlternatePresentation

This object provides an interface to the document’s particular alternate presentation. Use the Doc object method alternatePresentations to acquire an AlternatePresentation object.

See the PDF Reference for additional details on alternate presentations.

AlternatePresentation properties

active

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

boolean

R

This property is true if the presentation is currently active and false otherwise. When a presentation is active, it controls how the document that owns it is displayed.

Example: See the start method for an example.

type

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

string

R

The type of the alternate presentation. Currently, the only supported type is “SlideShow”.

AlternatePresentation methods

start

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Switches the document view into the alternate presentation mode and sets the active property to true. An exception is thrown if this or any other alternate presentation is already active.

Parameters

Parameter

Description

cOnStop

(optional) An expression to be evaluated by Acrobat when the presentation completes for any reason (as a result of a call to stop, an explicit user action, or the presentation logic itself).

cCommand

(optional) A command or script to pass to the alternate presentation. - This command is presentation-specific (not a JavaScript expression).

Example: Assume there is a named presentation called “MySlideShow” within the document.

// oMySlideShow is an AlternatePresentation object
oMySlideShow = this.alternatePresentations.MySlideShow;
if (!oMySlideShow.active) oMySlideShow.start();

Note that this.alternatePresentations is used to access the specified presentation by property name.

stop

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Stops the presentation and switches the document into normal (PDF) presentation. An exception is thrown if this presentation is not active.

Example: In this example, oMySlideShow is an AlternatePresentations object. See start for a related example.

// Stop the show if already active
if (oMySlideShow.active) oMySlideShow.stop();

annotAttachment

The annotAttachment object represents the file stored as the attachment for a FileAttachment type annotation. annotAttachment is similar to the Data object and represents the file content and metadata of the attachment.

See the PDF Reference for additional details on annotations.

annotAttachment properties

contentStream

Version (Key)

Save-Prefs

Security

Product

Type

Access

11.0

No

No

All

object

R

A ReadStream property representing the file attachment stream. This property enables access to the contents of the file attachment associated with an annotAttachment object.

A NotAllowedError is thrown and the method fails if it attempts to access the content of an embedded file attachment for which any of the following conditions is true (all file name extension matching is case-insensitive):

  • The attachment’s file name extension is “.SWF”. If a legitimate .SWF application or module run as part of Acrobat’s Rich Media Annotation or PDF Portfolio navigator is allowed access to the content bytes of .SWF embedded file attachments, it is possible that the legitimate .SWF will load a malicious .SWF.

Note

If you use the Data.MIMEType property to check whether a Data object represents a .SWF file, note that the MIME type for .SWF files is application/x-shockwave-flash.

  • The attachment’s file name extension is “.GIF”, “.JPG”, “.JPEG”, or “.PNG” and the first three bytes of its content have the header signature of a .SWF file (“FWS” or “CWS”). The reason for this security restriction is that the same ActionScriptflash.display.Loader class load() method that can be used to load GIF, JPEG, and PNG images can also be used to load a SWF file. If a malicious SWF file’s extension has been altered to that of one of these image types, the SWF could be loaded.

creationDate

Version (Key)

Save-Prefs

Security

Product

Type

Access

11.0

No

No

All

date

R

The date of creation of the attached file.

MIMEtype

Version (Key)

Save-Prefs

Security

Product

Type

Access

11.0

No

No

All

string

R

The MIME type of the attached file.

modDate

Version (Key)

Save-Prefs

Security

Product

Type

Access

11.0

No

No

No

date

R

The date of modification of the attached file.

name

Version (Key)

Save-Prefs

Security

Product

Type

Access

11.0

No

No

All

string

R

The name of the attached file.

pathname

Version (Key)

Save-Prefs

Security

Product

Type

Access

11.0

No

No

All

string

R

The pathname of the attached file.

size

Version (Key)

Save-Prefs

Security

Product

Type

Access

11.0

No

No

All

number

R

The size, in bytes, of the uncompressed attachment.

Example:

var annot = this.addAnnot({
    page: 0
    type: "FileAttachment",
    point: [400,500],
    author: "A. C. Robat",
    contents: "Call Smith to get help on this paragraph.",
    cAttachmentPath: "/d/a.pdf",
});
var attachObj = annot.attachment;
console.println("Name: " + attachObj.name);
console.println("Type: " + attachObj.MIMEType);
console.println("Size: "+ attachObj.size);
console.println("==============Content=================");
var stm = attachObj.contentStream;
console.println(util.stringFromStream(stm));

Annotation

This object represents an Acrobat annotation. Annotations can be created using the Acrobat annotation tool or by using the Doc object method addAnnot.

Before an annotation can be accessed, it must be bound to a JavaScript variable through a Doc object method such as getAnnot :

var a = this.getAnnot(0, "Important");

The script can then manipulate the annotation named “Important” on page 1 (0-based page numbering system) by means of the variable a. For example, the following code first stores the type of annotation in the variable thetype, then changes the author to “John Q. Public”.

var thetype = a.type;          // read property
a.author = "John Q. Public";   // write property

Another way of accessing the Annotation object is through the Doc object getAnnots method.

Note

In Adobe Reader 5.1 or later, you can get the value of any annotation property except contents. The ability to set these properties depends on Comments document rights, as indicated by the C icon.

Note

The user interface in Acrobat refers to annotations as comments .

Annotation types

Annotations are of different types, as reflected in the type property. Each type is listed in the table below, along with all documented properties returned by the getProps method.

Annotation type

Properties

Caret

author, borderEffectIntensity, borderEffectStyle, caretSymbol, contents, creationDate, delay, hidden, inReplyTo, intent, lock, modDate, name, noView, opacity, page, popupOpen, popupRect, print, readOnly, rect, refType, richContents, rotate, seqNum, strokeColor, style, subject, toggleNoView, type, width

Circle

author, borderEffectIntensity, borderEffectStyle, contents, creationDate, dash, delay, fillColor, hidden, inReplyTo, intent, lock, modDate, name, noView, opacity, page, popupOpen, popupRect, print, readOnly, rect, refType, richContents, rotate, seqNum, strokeColor, style, subject, toggleNoView, type, width

FileAttachment

attachIcon, attachment, author, borderEffectIntensity, borderEffectStyle, cAttachmentPath, contents, creationDate, delay, hidden, inReplyTo, intent, lock, modDate, name, noView, opacity, page, point, print, readOnly, rect, refType, richContents, rotate, seqNum, strokeColor, style, subject, toggleNoView, type, width

FreeText

alignment, author, borderEffectIntensity, borderEffectStyle, callout, contents, creationDate, dash, delay, fillColor, hidden, inReplyTo, intent, lineEnding, lock, modDate, name, noView, opacity, page, print, readOnly, rect, refType, richContents, richDefaults, rotate, seqNum, strokeColor, style, subject, textFont, textSize, toggleNoView, type, width

Highlight

author, borderEffectIntensity, borderEffectStyle, contents, creationDate, delay, hidden, inReplyTo, intent, lock, modDate, name, noView, opacity, page, popupOpen, popupRect, print, quads, readOnly, rect, refType, richContents, rotate, seqNum, strokeColor, style, subject, toggleNoView, type, width

Ink

author, borderEffectIntensity, borderEffectStyle, contents, creationDate, dash, delay, gestures, hidden, inReplyTo, intent, lock, modDate, name, noView, opacity, page, popupOpen, popupRect, print, readOnly, rect, refType, richContents, rotate, seqNum, strokeColor, style, subject, toggleNoView, type, width

Line

arrowBegin, arrowEnd, author, borderEffectIntensity, borderEffectStyle, contents, creationDate, dash, delay, doCaption, fillColor, hidden, inReplyTo, intent, leaderExtend, leaderLength, lock, modDate, name, noView, opacity, page, points, popupOpen, popupRect, print, readOnly, rect, refType, richContents, rotate, seqNum, strokeColor, style, subject, toggleNoView, type, width

Polygon

author, borderEffectIntensity, borderEffectStyle, contents, creationDate, dash, delay, fillColor, hidden, inReplyTo, intent, lock, modDate, name, noView, opacity, page, popupOpen, popupRect, print, readOnly, rect, refType, richContents, rotate, seqNum, strokeColor, style, subject, toggleNoView, type, vertices, width

PolyLine

arrowBegin, arrowEnd, author, borderEffectIntensity, borderEffectStyle, contents, creationDate, dash, delay, fillColor, hidden, inReplyTo, intent, lock, modDate, name, noView, opacity, page, popupOpen, popupRect, print, readOnly, rect, refType, richContents, rotate, seqNum, strokeColor, style, subject, toggleNoView, type, vertices, width

Redact

In addition to all the usual properites of a markup type annotation (see for example, the property list of the Highlight type), the properties alignment, overlayText and repeat are particular to the Redact annotation.

Sound

author, borderEffectIntensity, borderEffectStyle, contents, creationDate, delay, hidden, inReplyTo, intent, lock, modDate, name, noView, opacity, page, point, print, readOnly, rect, refType, richContents, rotate, seqNum, soundIcon, strokeColor, style, subject, toggleNoView, type, width

Square

author, borderEffectIntensity, borderEffectStyle, contents, creationDate, dash, delay, fillColor, hidden, inReplyTo, intent, lock, modDate, name, noView, opacity, page, popupOpen, popupRect, print, readOnly, rect, refType, richContents, rotate, seqNum, strokeColor, style, subject, toggleNoView, type, width

Squiggly

author, borderEffectIntensity, borderEffectStyle, contents, creationDate, delay, hidden, inReplyTo, intent, lock, modDate, name, noView, opacity, page, popupOpen, popupRect, print, quads, readOnly, rect, refType, richContents, rotate, seqNum, strokeColor, style, subject, toggleNoView, type, width

Stamp

AP, author, borderEffectIntensity, borderEffectStyle, contents, creationDate, delay, hidden, inReplyTo, intent, lock, modDate, name, noView, opacity, page, popupOpen, popupRect, print, readOnly, rect, refType, rotate, seqNum, strokeColor, style, subject, toggleNoView, type

StrikeOut

author, borderEffectIntensity, borderEffectStyle, contents, creationDate, delay, hidden, inReplyTo, intent, lock, modDate, name, noView, opacity, page, popupOpen, popupRect, print, quads, readOnly, rect, refType, richContents, rotate, seqNum, strokeColor, style, subject, toggleNoView, type, width

Text

author, borderEffectIntensity, borderEffectStyle, contents, creationDate, delay, hidden, inReplyTo, intent, lock, modDate, name, noView, noteIcon, opacity, page, point, popupOpen, popupRect, print, readOnly, rect, refType, richContents, rotate, seqNum, state, stateModel, strokeColor, style, subject, toggleNoView, type, width

Underline

author, borderEffectIntensity, borderEffectStyle, contents, creationDate, delay, hidden, inReplyTo, intent, lock, modDate, name, noView, opacity, page, popupOpen, popupRect, print, quads, readOnly, rect, refType, richContents, rotate, seqNum, strokeColor, style, subject, toggleNoView, type, width

Annotation properties

The PDF Reference documents all Annotation properties and specifies how they are stored.

Some property values are stored in the PDF document as names and others are stored as strings (see the PDF Reference for details). A property stored as a name can have only 127 characters.

Examples of properties that have a 127-character limit include AP, beginArrow, endArrow, attachIcon, noteIcon, and soundIcon.

alignment

Version (Key)

Save-Prefs

Security

Product

Type

Access

11.0

D

No

C

number

R/W

Controls the alignment of the text for a FreeText annotation.

Beginning with version 8.0, when the annotation is of type Redact, this property determines the alignment of the overlayText.

Alignment

Value

Left aligned

0

Centered

1

Right aligned

2

Annotations: FreeText, Redact

attachment

Version (Key)

Save-Prefs

Security

Product

Type

Access

11.0

No

No

All

object

R

Represents the annotAttachment object for a FileAttachment type annotation.

Beginning with version 11.0, when the annotation is of type FileAttachment, this property determines the object to be attached. For annotation types other than FileAttachment, an undefined value is returned. The ESErrorGenral exception occurs if the attachment is invalid.

Annotations: FileAttachment

Example:

var annot = this.addAnnot({
       page: 0,
       type: "FileAttachment",
       point: [400,500],
       author: "A. C. Robat",
       contents: "Call Smith to get help on this paragraph.",
       cAttachmentPath: "/d/a.pdf"
   });
   var attachmentObj = annot.attachment;

AP

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

string

R/W

The named appearance of the stamp to be used in displaying a stamp annotation. The names of the standard stamp annotations are given below:

  • Approved

  • AsIs

  • Confidential

  • Departmental

  • Draft

  • Experimental

  • Expired

  • Final

  • ForComment

  • ForPublicRelease

  • NotApproved

  • NotForPublicRelease

  • Sold

  • TopSecret

Annotations: Stamp

Example: Programmatically add a stamp annotation.

var annot = this.addAnnot({
    page: 0,
    type: "Stamp",
    author: "A. C. Robat",
    name: "myStamp",
    rect: [400, 400, 550, 500],
    contents: "Try it again, this time with order and method!",
    AP: "NotApproved" });

Note

The name of a particular stamp can be found by opening the PDF file in the Stamps folder that contains the stamp in question. For a list of stamp names currently in use in the document, see the Doc object icons property.

arrowBegin

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

string

R/W

Determines the line cap style that specifies the shape to be used at the beginning of a line annotation. Permissible values are:

  • None (default)

  • OpenArrow

  • ClosedArrow

  • ROpenArrow* // Acrobat 6.0

  • RClosedArrow* // Acrobat 6.0

  • Butt* // Acrobat 6.0

  • Diamond

  • Circle

  • Square

  • Slash // Acrobat 7.0

Annotations: Line, PolyLine

Example: See the setProps method.

arrowEnd

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

string

R/W

Determines the line cap style that specifies the shape to be used at the end of a line annotation. The following list shows the allowed values:

  • None (default)

  • OpenArrow

  • ClosedArrow

  • ROpenArrow* // Acrobat 6.0

  • RClosedArrow* // Acrobat 6.0

  • Butt* // Acrobat 6.0

  • Diamond

  • Circle

  • Square

  • Slash // Acrobat 7.0

Annotations: Line, PolyLine

Example: See the setProps method.

attachIcon

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

string

R/W

The name of an icon to be used in displaying the annotation. Possible values include:

  • Paperclip

  • PushPin (default)

  • Graph

  • Tag

Annotations: FileAttachment

author

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

string

R/W

Gets or sets the author of the annotation.

Annotations: All

Example: See the contents property.

borderEffectIntensity

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

D

No

C

string

R/W

The intensity of the border effect, if any. This represents how cloudy a cloudy rectangle, polygon, or oval is.

Annotations: All

borderEffectStyle

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

D

No

C

string

R/W

If non-empty, the name of a border effect style. Currently, the only supported border effects are the empty string (nothing) or “C” for cloudy.

Annotations: All

callout

Version (Key)

Save-Prefs

Security

Product

Type

Access

7.0

D

No

C

array

R/W

Annotations: FreeText

cAttachmentPath

Version (Key)

Save-Prefs

Security

Product

Type

Access

11.0

D

No

C

string

W

(Optional) Represents the device-independent path of the file to be attached. If this property is not set, the user is prompted to select a data file using the File Open dialog box. This property does not apply to annotation types other than FileAttachment. See the PDF Reference for additional details.

Annotations: FileAttachment

Example:

var annot = this.addAnnot({
       page: 0,
       type: "FileAttachment",
       point: [400,500],
       author: "A. C. Robat",
       contents: "Call Smith to get help on this paragraph.",
       cAttachmentPath: "/d/a.pdf"
   });

caretSymbol

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

D

No

C

string

R/W

The symbol associated with a Caret annotation, which is a visual symbol that indicates the presence of text edits. Valid values are “” (nothing), “P” (paragraph symbol) or “S” (space symbol).

Annotations: Caret

contents

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

string

R/W

Accesses the contents of any annotation that has a pop-up window. For sound and file attachment annotations, specifies the text to be displayed as a description.

Annotations: All

Example: Create a text annotation, with author and contents specified.

var annot = this.addAnnot({
    page: 0,
    type: "Text",
    point: [400,500],
    author: "A. C. Robat",
    contents: "Call Smith to get help on this paragraph.",
    noteIcon: "Help"
});

See also the Doc object addAnnot method.

creationDate

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

C

date

R

The date and time when the annotation was created.

Annotations: All

dash

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

D

No

C

array

R/W

A dash array defining a pattern of dashes and gaps to be used in drawing a dashed border. For example, a value of [3, 2] specifies a border drawn with 3-point dashes alternating with 2-point gaps.

To set the dash array, the style property must be set to D.

Annotations: FreeText, Line, PolyLine, Polygon, Circle, Square, Ink

Example: Assuming annot is an Annotation object, this example changes the border to dashed.

annot.setProps({ style: "D", dash: [3,2] });

See also the example following the delay property.

delay

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

No

No

C

boolean

R/W

If true, property changes to the annotation are queued and then executed when delay is set back to false. (Similar to the Field object delay property.)

Annotations: All

Example: Assuming annot is an Annotation object, the code below changes the border to dashed.

annot.delay=true;
annot.style = "D";
annot.dash = [4,3];
annot.delay = false;

doc

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

No

No

C

object

R

The Doc object of the document in which the annotation resides.

Annotations: All

Example: Construct an annotation, and illustrate the use of the doc property.

var inch = 72;
var annot = this.addAnnot({
    page: 0,
    type: "Square",
    rect: [1*inch, 3*inch, 2*inch, 3.5*inch]
});
/* displays, for example, "file:///C|/Adobe/Annots/myDoc.pdf" */
console.println(annot.doc.URL);

doCaption

Version (Key)

Save-Prefs

Security

Product

Type

Access

7.0

D

No

C

boolean

R/W

Annotations: Line

Example: See the example following the points property.

fillColor

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

color

R/W

Sets the background color for circle, square, line, polygon, polyline, and free text annotations. Values are defined by using transparent, gray, RGB or CMYK color. See Color arrays for information on defining color arrays and how values are used with this property.

Annotations: Circle, Square, Line, Polygon, PolyLine, FreeText

Example: Create a Circle annotation and set the background color.

var annot = this.addAnnot(
{
    type: "Circle",
    page: 0,
    rect: [200,200,400,300],
    author: "A. C. Robat",
    name: "myCircle",
    popupOpen: true,
    popupRect: [200,100,400,200],
    contents: "Hi World!",
    strokeColor: color.red,
    fillColor: ["RGB",1,1,.855]
});

gestures

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

array

R/W

An array of arrays, each representing a stroked path. Each array is a series of alternating x and y coordinates in default user space, specifying points along the path. When drawn, the points are connected by straight lines or curves in an implementation-dependent way. See the PDF Reference for more details.

Annotations: Ink

hidden

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

boolean

R/W

If true, the annotation is not shown and there is no user interaction, display, or printing of the annotation.

Annotations: All

inReplyTo

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

D

No

C

string

R/W

If non-empty, specifies the name value of the annotation that this annotation is in reply to.

Annotations: All

intent

Version (Key)

Save-Prefs

Security

Product

Type

Access

7.0

D

No

C

string

R/W

This property allows a markup annotation type to behave differently, depending on the intended use of the annotation. For example, the Callout Tool is a free text annotation with intent set to FreeTextCallout.

Though this property is defined for all annotations, currently, only free text, polygon, and line annotations have non-empty values for intent.

Annotations: All

The table below lists the tools available through the UI for creating annotations with special appearances.

UI

Annotation type

Intent

Callout Tool

FreeText

FreeTextCallout

Cloud Tool

Polygon

PolygonCloud

Arrow Tool

Line

LineArrow

Dimensioning Tool

Line

LineDimension

leaderExtend

Version (Key)

Save-Prefs

Security

Product

Type

Access

7.0

D

No

C

number

R/W

Specifies the length of leader line extensions that extend from both endpoints of the line, perpendicular to the line. These lines extend from the line proper 180 degrees from the leader lines. The value should always be greater than or equal to zero.

The default is zero (no leader line extension).

Annotations: Line

leaderLength

Version (Key)

Save-Prefs

Security

Product

Type

Access

7.0

D

No

C

number

R/W

Specifies the length of leader lines that extend from both endpoints of the line, perpendicular to the line. The value may be negative to specify an alternate orientation of the leader lines.

The default is 0 (no leader line).

Annotations: Line

lineEnding

Version (Key)

Save-Prefs

Security

Product

Type

Access

7.0

D

No

C

string

R/W

This property determines how the end of a callout line is stroked. It is relevant only for a free text annotation when the value of intent is FreeTextCallout. Possible values include:

  • None (default)

  • OpenArrow

  • ClosedArrow

  • ROpenArrow: Acrobat 6.0

  • RClosedArrow: Acrobat 6.0

  • Butt: Acrobat 6.0

  • Diamond

  • Circle

  • Square

  • Slash: Acrobat 7.0

Annotations: FreeText

lock

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

boolean

R/W

If true, the annotation is locked, which is equivalent to readOnly except that the annotation is accessible through the properties dialog box in the UI.

Annotations: All

modDate

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

No

No

C

date

R/W

The last modification date for the annotation.

Annotations: All

Example: Print the modification date to the console.

console.println(util.printd("mmmm dd, yyyy", annot.modDate));

name

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

D

No

C

string

R/W

The name of an annotation. This value can be used by the Doc object getAnnot method to find and access the properties and methods of the annotation.

Annotations: All

Example: Locate the annotation named myNote and appends a comment.

var gannot = this.getAnnot(0, "myNote");
gannot.contents += "rrDon't forget to check with Smith";

noteIcon

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

string

R/W

The name of an icon to be used in displaying the annotation. Possible values include:

  • Check

  • Circle

  • Comment

  • Cross

  • Help

  • Insert

  • Key

  • NewParagraph

  • Note(default)

  • Paragraph

  • RightArrow

  • RightPointer

  • Star

  • UpArrow

  • UpLeftArrow

Annotations: Text

Example: See the contents property.

noView

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

boolean

R/W

If true, the annotation is hidden, but if the annotation has an appearance, that appearance should be used for printing only.

Annotations: All

Example: See the toggleNoView property.

opacity

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

number

R/W

The constant opacity value to be used in painting the annotation. This value applies to all visible elements of the annotation in its closed state (including its background and border), but not to the pop-up window that appears when the annotation is opened. Permissible values are 0.0 - 1.0. A value of 0.5 makes the annotation semitransparent.

Annotations: All

overlayText

Version (Key)

Save-Prefs

Security

Product

Type

Access

8.0

D

No

C

string

R/W

A text string specifying the overlay text that should be drawn over the redacted region after the affected content has been removed.

Annotations: Redact

Example: Set the redaction properties of a particular redaction annotation.

var a = this.getAnnots();                              // get all annotations in doc
var r = a[0]           ;                               // the first one is Redact type
r.setProps({                                           // now set its properties
   overlayText: " A.C. Robat ",
   alignment: 0,
   repeat: true,
   fillColor:color.blue,
   textColor: color.green
});

There is a popup associated with a Redact annotation, now add content to this popup note.

r.setProps({ contents: "Shall we redact this paragraph?" });

See also the applyRedactions method of the Doc object.

page

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

integer

R/W

The page on which the annotation resides.

Annotations: All

Example: The following code moves the Annotation object annot from its current page to page 3 (0-based page numbering system).

annot.page = 2;

point

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

array

R/W

An array of two numbers, [ x ul, y ul ] that specifies the upper left-hand corner in default user space of the icon for a text, sound or file attachment annotation.

Annotations: Text, Sound, FileAttachment

Example: Place a help note icon at specified coordinates. The icon is located at the upper right corner of the popup note.

var annot = this.addAnnot({
    page: 0,
    type: "Text",
    point: [400,500],
    contents: "Call Smith to get help on this paragraph.",
    popupRect: [400,400,550,500],
    popupOpen: true,
    noteIcon: "Help"
});

See also the noteIcon property and the Doc object addAnnot method.

points

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

array

R/W

An array of two points, [[ x 1 , y 1 ], [ x 2 , y 2 ]], specifying the starting and ending coordinates of the line in default user space.

Annotations: Line

Example: Draw a line between two specified points.

var annot = this.addAnnot({
    type: "Line",
    page: 0,
    author: "A. C. Robat",
    doCaption: true,
    contents: "Look at this again!",
    points: [[10,40],[200,200]],
});

See the arrowBegin and arrowEnd properties, the setProps method, and the Doc object addAnnot method.

popupOpen

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

boolean

R/W

If true, the pop-up text note appears open when the page is displayed.

Annotations: All except FreeText, Sound, FileAttachment

Example: See the print property.

popupRect

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

array

R/W

An array of four numbers [ x ll, y ll, x ur , y ur ] specifying the lower-left x, lower-left y, upper-right x, and upper-right y coordinates—in default user space—of the rectangle of the pop-up annotation associated with a parent annotation. It defines the location of the pop-up annotation on the page.

Annotations: All except FreeText, Sound, FileAttachment

Example: See the print property.

print

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

boolean

R/W

Indicates whether the annotation should be printed (true) or not (false).

Annotations: All

quads

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

array

R/W

An array of 8 x n numbers specifying the coordinates of n quadrilaterals in default user space. Each quadrilateral encompasses a word or group of contiguous words in the text underlying the annotation. See the PDF Reference for more details. The quads for a word can be obtained through calls to the Doc object getPageNthWordQuads method.

Annotations: Highlight, StrikeOut, Underline, Squiggly,Redact

Example: See the Doc object getPageNthWordQuads method.

rect

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

array

R/W

The rect array consists of four numbers [ x ll, y ll, x ur, y ur ] specifying the lower-left x, lower-left y, upper-right x, and upper-right y coordinates—in default user space—of the rectangle defining the location of the annotation on the page. See also the popupRect property.

Annotations: All

readOnly

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

boolean

R/W

Annotations: All

refType

Version (Key)

Save-Prefs

Security

Product

Type

Access

7.0

D

No

C

string

R/W

The reference type of the annotation. The property distinguishes whether inReplyTo indicates a plain threaded discussion relationship or a group relationship. Recognized values are “R” and “Group”. See the PDF Reference for additional details.

Annotations: All

repeat

Version (Key)

Save-Prefs

Security

Product

Type

Access

8.0

D

No

C

boolean

R/W

If true, the text specified by overlayText should be repeated to fill the redacted region after the affected content has been removed. Default value: false.

Annotations: Redact

richContents

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

D

No

C

Array of Span objects

R/W

This property gets the text contents and formatting of an annotation. The rich text contents are represented as an array of Span objects containing the text contents and formatting of the annotation.

Annotations: All except Sound, FileAttachment

Example: Create a text annotation and give it some rich text contents.

var annot = this.addAnnot({
    page: 0,
    type: "Text",
    point: [72,500],
    popupRect: [72, 500,6*72,500-2*72],
    popupOpen: true,
    noteIcon: "Help"
});

var spans = new Array();
spans[0] = new Object();
spans[0].text = "Attention:r";
spans[0].textColor = color.blue;
spans[0].textSize = 18;

spans[1] = new Object();
spans[1].text = "Adobe Acrobat 6.0r";
spans[1].textColor = color.red;
spans[1].textSize = 20;
spans[1].alignment = "center";

spans[2] = new Object();
spans[2].text = "will soon be here!";
spans[2].textColor = color.green;
spans[2].fontStyle = "italic";
spans[2].underline = true;
spans[2].alignment = "right";

// Now give the rich field a rich value
annot.richContents = spans;

See also the Field object richValue method and the event object methods richValue, richChange, and richChangeEx for examples of using the Span object.

richDefaults

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

D

No

C

Span object

R/W

This property defines the default style attributes for a free text annotation. See the description of the Field object defaultStyle property for additional details.

Annotations: FreeText

rotate

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

integer

R/W

The number of degrees (0, 90, 180, 270) the annotation is rotated counterclockwise relative to the page. This property is only significant for free text annotations.

Annotations: FreeText

seqNum

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

No

No

C

integer

R

A read-only sequence number for the annotation on the page.

Annotations: All

soundIcon

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

string

R/W

The name of an icon to be used in displaying the sound annotation. A value of “Speaker” is recognized.

Annotations: Sound

state

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

D

No

C

string

R/W

The state of the text annotation. The values of this property depend on the stateModel. For a state model of Marked, values are Marked and Unmarked. For a Review state model, the values are Accepted, Rejected, Cancelled, Completed and None.

Annotations: Text

stateModel

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

D

No

C

string

R/W

Beginning with Acrobat 6.0, annotations may have an author-specific state associated with them. The state is specified by a separate text annotation that refers to the original annotation by means of its IRT entry (see the inReplyTo property). There are two types of state models, “Marked” and “Review”.

Annotations: Text

See also the getStateInModel method.

strokeColor

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

color

R/W

Sets the appearance color of the annotation. Values are defined by using transparent, gray, RGB or CMYK color. In the case of a free text annotation, strokeColor sets the border and text colors. See Color arrays for information on defining color arrays and how values are used with this property.

Annotations: All

Example: Make a text note red.

var annot = this.addAnnot({type: "Text"});
annot.strokeColor = color.red;

style

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

string

R/W

This property gets and sets the border style. Recognized values are S (solid) and D (dashed). The style property is defined for all annotation types but is only relevant for line, free text, circle, square, polyline, polygon and ink annotations.

Annotations: All

See the dash property for an example.

subject

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

D

No

C

string

R/W

Text representing a short description of the subject being addressed by the annotation. The text appears in the title bar of the pop-up window, if there is one, or the properties dialog box.

Annotations: All

textFont

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

string

R/W

Determines the font that is used when laying out text in a free text annotation. Valid fonts are defined as properties of the font object (see the Field object textFont property).

An arbitrary font can be used when laying out a free text annotation by setting the value of textFont equal to a string that represents the PostScript name of the font.

Annotations: FreeText

Example: Create a FreeText annotation using the Helvetica font.

var annot = this.addAnnot({
    page: 0,
    type: "FreeText",
    textFont: font.Helv, // or, textFont: "Viva-Regular",
    textSize: 10,
    rect: [200, 300, 200+150, 300+3*12], // height for three lines
    width: 1,
    alignment: 1 });

textSize

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

number

R/W

The text size (in points) for a free text annotation. Valid text sizes include zero and the range from 4 to 144, inclusive. Zero indicates the largest point size that allows all the text to fit in the annotation’s rectangle.

Annotations: FreeText

Example: See the textFont property.

toggleNoView

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

D

No

C

string

R/W

If true, the noView flag is toggled when the mouse hovers over the annotation or the annotation is selected.

If an annotation has both the noView and toggleNoView flags set, the annotation is usually invisible. However, when the mouse is over it or it is selected, it becomes visible.

Annotations: All

type

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

No

No

C

string

R

The type of annotation. The type of an annotation can only be set within the object-literal argument of the Doc object addAnnot method. The valid values are:

  • Text

  • FreeText

  • Line

  • Square

  • Circle

  • Polygon

  • PolyLine

  • Highlight

  • Underline

  • Squiggly

  • StrikeOut

  • Stamp

  • Caret

  • Ink

  • FileAttachment

  • Sound

Annotations: All

vertices

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

D

No

C

Array of arrays

R/W

An array of coordinate arrays representing the alternating horizontal and vertical coordinates, respectively, of each vertex, in default user space of a polygon or polyline annotation. See the PDF Reference for details.

Annotations: Polygon, PolyLine

width

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

C

number

R/W

The border width in points. If this value is 0, no border is drawn. The default value is 1.

Annotations: Square, Circle, Line, Ink, FreeText

Annotation methods

destroy

Version (Key)

Save-Prefs

Security

Product

5.0

D

No

C

Destroys the annotation, removing it from the page. The object becomes invalid.

Example: Remove all “FreeText” annotations on page 0.

var annots = this.getAnnots({ nPage:0 });
for (var i = 0; i < annots.length; i++)
    if (annots[i].type == "FreeText") annots[i].destroy();

getProps

Version (Key)

Save-Prefs

Security

Product

6.0

D

No

C

Get the collected properties of an annotation. Can be used to copy an annotation.

Returns

An object literal of the properties of the annotation. The object literal is just like the one passed to the Doc object addAnnot method.

Example 1: Copy a given annotation to every page in the document.

var annot = this.addAnnot({
    page: 0,
    type: "Text",
    rect: [40, 40, 140, 140]
});

// Make a copy of the properties of annot
var copy_props = annot.getProps();

// Now create a new annot with the same properties on every page
var numpages = this.numPages;
for (var i=0; i < numpages; i++) {
    var copy_annot = this.addAnnot(copy_props);
    // but move it to page i
    copy_annot.page=i;
}

Example 2: Display all properties and values of an annotation.

var a = this.getAnnots(0);     // get all annots on page 0
if ( a != null ) {
    var p = a[0].getProps();     // get the properties of first one
    for ( o in p ) console.println( o + " : " + p[o] );
}

getStateInModel

Version (Key)

Save-Prefs

Security

Product

6.0

D

No

C

Gets the current state of the annotation in the context of a state model. See also the transitionToState method.

Parameters

Parameter

Description

cStateModel

The state model to determine the state of the annotation.

Returns

The result is an array of the identifiers for the current state of the annotation:

  • If the state model was defined to be exclusive, there is only a single state (or no states if the state has not been set).

  • If the state model is non-exclusive, there may be multiple states (or no entries if the state has not been set and there is no default).

Example: Report on the status of all annotations on all pages of this document.

annots = this.getAnnots()
for ( var i= 0; i< annots.length; i++) {
    states = annots[i].getStateInModel("Review");
    if ( states.length > 0 ) {
        for(j = 0; j < states.length; j++)
        {
            var d = util.printd(2, states[j].modDate);
            var s = states[j].state;
            var a = states[j].author;

            console.println(annots[i].type + ": " + a + " "
                + s + " " + d + "on page "
                + (annots[i].page+1) );
        }

    }
}

setProps

Version (Key)

Save-Prefs

Security

Product

6.0

D

No

C

Parameters

Parameter

Description

object literal

A generic object that specifies the properties of the Annotation object to be created (such as type, rect, and page). This object is the same as the parameter of the Doc object addAnnot method.

Returns

The Annotation object

Example: Set various properties of a Line annotation.

var annot = this.addAnnot({type: "Line"})
annot.setProps({
    page: 0,
    points: [[10,40],[200,200]],
    strokeColor: color.red,
    author: "A. C. Robat",
    contents: "Check with Jones on this point.",
    popupOpen: true,
    popupRect: [200, 100, 400, 200], // Place rect at tip of the arrow
    arrowBegin: "Diamond",
    arrowEnd: "OpenArrow"
});

transitionToState

Version (Key)

Save-Prefs

Security

Product

6.0

D

No

C

Sets the state of the annotation to cState by performing a state transition. The state transition is recorded in the audit trail of the annotation.

See also the getStateInModel method.

Note

For the states to work correctly in a multiuser environment, all users must have the same state model definitions. Therefore, it is best to place state model definitions in a folder-level JavaScript file that can be distributed to all users or installed on all systems.

Parameters

Parameter

Description

cStateModel

The state model in which to perform the state transition. cStateModel must have been previously added by calling the Collab method addStateModel.

cState

A valid state in the state model to transition to.

Example: Define a custom set of transition states, then set the state of an annotation.

try {
    // Create a document
    var myDoc = app.newDoc();
    // Create an annot
    var myAnnot = myDoc.addAnnot
    ({
        page: 0,
        type: "Text",
        point: [300,400],
        name: "myAnnot",
    });
    // Create the state model
    var myStates = new Object();
    myStates["initial"] = {cUIName: "Haven't reviewed it"};
    myStates["approved"] = {cUIName: "I approve"};
    myStates["rejected"] = {cUIName: "Forget it"};
    myStates["resubmit"] = {cUIName: "Make some changes"};
    Collab.addStateModel({
        cName: "ReviewStates",
        cUIName: "My Review",
        oStates: myStates,
        cDefault: "initial"
    });
} catch(e) { console.println(e); }
// Change the states
myAnnot.transitionToState("ReviewStates", "resubmit");
myAnnot.transitionToState("ReviewStates", "approved");

AnnotRichMedia

An AnnotRichMedia object represents a particular rich media annotation; that is, an annotation created using one of the tools 3D, Flash, Video, or Sound from the Multimedia toolbar. The AnnotRichMedia object can be acquired from the getAnnotRichMedia and getAnnotsRichMedia methods of the Doc object.

AnnotRichMedia properties

activated

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

boolean

R/W

A Boolean value that indicates whether the annotation is enabled and interactive (true) or just displaying the poster artwork (false). Setting this property to true activates the annotation.

context3D

Version (Key)

Save-Prefs

Security

Product

Type

Access

9.0

No

No

All

global object or undefined

R

If activated is true and subtype is "3D", this property returns the global scripting context of the annotation (a global object containing the 3D scene.) (See the JS 3D API Reference for more information.) If activated is false or subtype is not "3D", this property returns undefined.

name

Version (Key)

Save-Prefs

Security

Product

Type

Access

9.0

No

No

All

string

R

The name of the rich media annotation.

page

Version (Key)

Save-Prefs

Security

Product

Type

Access

9.0

No

No

All

integer

R

The 0-based page number of the page containing the annotation.

rect

Version (Key)

Save-Prefs

Security

Product

Type

Access

9.0

No

No

All

array

R/W

Returns an array of four numbers [xll, yll, xur, yur] specifying the lower-left x, lower-left y, upper-right x and upper-right y coordinates, in default user space, of the rectangle defining the location of the annotation on the page.

subtype

Version (Key)

Save-Prefs

Security

Product

Type

Access

9.0

No

No

All

string

R

The subtype of the annotation. The property will have a value of "3D", "Flash", "Video", or "Sound".

AnnotRichMedia methods

callAS

Version (Key)

Save-Prefs

Security

Product

9.0

No

No

All

Calls into ActionScript with the ExternalInterface calling convention to an exposed method
(ExternalInterface.addCallback in ActionScript). The callAS method returns the return value of the method specified as the first parameter.

Note

The JS 3D API Reference has the call method of the FlashMovie object that uses the same mechanism as the callAS method.

Parameters

Parameter

Description

methodName

The string name of the exposed method in ActionScript to be called.

arguments

A series of arguments of arbitrary type to be passed to the ActionScript method being called.

Returns

The return value from the called function, which can be of any type.

The Multimedia Operation (Acrobat 9 and later) is an Action type for rich media annotations that can be used to perform Play, Pause, Rewind, Next Chapter Point, Previous Chapter Point, Seek to time, Mute, Volume, and Custom actions. The same actions can be executed through the callAS method.

The following lists some custom ActionScript methods that are visible through the Multimedia Operations dialog box, and can be used in the callAS method.

  • Custom ActionScript Methods

  • multimedia_play():void Play the video or sound clip from the current location.

  • multimedia_pause():void Pause playback of the current media.

  • multimedia_rewind():void Rewind the media clip to the beginning. This method does not pause the clip.

  • multimedia_nextCuePoint():void Move the play head to the next cue (chapter) point.

  • multimedia_prevCuePoint():void Move the play head to the previous (chapter) point.

  • multimedia_seek(time:Number):void Move the play location to an offset of time from the beginning of the media, where time is measured in seconds.

  • multimedia_mute():void Mute the audio of the media.

  • multimedia_volume(volume:Number):void Set the volume level. The volume is a number between 0 and 1 inclusive. A value of 0 mutes the audio, while a volume of 1 sets the volume level to the maximum level.

Example: In this example, it is assumed that a video has been embedded in the current PDF using the Video tool, and that the video has a number of Chapter Points, perhaps created through the Video tab of the Insert Video dialog box. Below are several Run a JavaScript actions for buttons that control the video. The annotation targeted is the first rich media annotation on the first page.

// Code for a Play button
var rm = this.getAnnotsRichMedia(0)[0];
if (!rm.activated) rm.activated=true;
rm.callAS("multimedia_play");

// Code for a Pause button
var rm = this.getAnnotsRichMedia(0)[0];
if (rm.activated) { rm.callAS("multimedia_pause"); }

// Code for a Next Chapter Point button
var rm = this.getAnnotsRichMedia(0)[0];
if (rm.activated) { rm.callAS("multimedia_nextCuePoint"); }

// Code for a simple Volume button, set volume to the 50% level.
var rm = this.getAnnotsRichMedia(0)[0];
if (rm.activated) { rm.callAS("multimedia_volume", 0.5); }

Annot3D

An Annot3D object represents a particular Acrobat 3D annotation; that is, an annotation created using the Acrobat 3D Tool. The Annot3D object can be acquired from the Doc object methods getAnnot3D and getAnnots3D.

Annot3D properties

activated

Version (Key)

Save-Prefs

Security

Product

Type

Access

7.0

No

No

All

boolean

R/W

A Boolean value that indicates whether the annotation is displaying the 3D artwork (true) or just the posterboard picture (false).

See the context3D property.

context3D

Version (Key)

Save-Prefs

Security

Product

Type

Access

7.0

No

No

All

global object

R

If activated is true, this property returns the context of the 3D annotation (a global object containing the 3D scene.) See the JS 3D API Reference for more information. If activated is false, this property returns undefined.

innerRect

Version (Key)

Save-Prefs

Security

Product

Type

Access

7.0

No

No

All

array

R/W

An array of four numbers [x ll, y ll, x ur, y ur ] specifying the lower-left x, lower-left y, upper-right x and upper-right y coordinates, in the coordinate system of the annotation (lower-left is [0, 0], top right is [width, height]), of the 3D annotation’s 3DB box, where the 3D artwork is rendered.

name

Version (Key)

Save-Prefs

Security

Product

Type

Access

7.0

No

No

All

string

R

The name of the annotation.

page

Version (Key)

Save-Prefs

Security

Product

Type

Access

7.0

No

No

All

integer

R

The 0-based page number of the page containing the annotation.

rect

Version (Key)

Save-Prefs

Security

Product

Type

Access

7.0

No

No

All

array

R/W

Returns an array of four numbers [x ll, y ll, x ur, y ur ] specifying the lower-left x, lower-left y, upper-right x and upper-right y coordinates, in default user space, of the rectangle defining the location of the annotation on the page.

app

A static JavaScript object that represents the Acrobat application. It defines a number of Acrobat-specific functions plus a variety of utility routines and convenience functions.

app properties

activeDocs

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

No

Yes

All

array

R

An array containing the Doc object for each active document. If no documents are active, activeDocs returns nothing; that is, it has the same behavior as d = new Array(0) in core JavaScript.

In versions of Acrobat earlier than 7.0, executing the script d = app.activeDocs in the console returned [object Global] to the console. Beginning with Acrobat 7.0, no toString() value is output to the console.

Note

You should be aware of the following version-related information:

  • In Acrobat 5.0, this property returns an array containing the Doc object for each active document.

  • In Acrobat 5.0.5, this property was changed to return an array of Doc objects of only those open documents that have the Doc object disclosed property set to true.

  • Beginning with the Acrobat 5.0.5 Accessibility and Forms Patch and continuing with Acrobat 6.0 and later, the behavior is as follows: During a batch, console or menu event, activeDocs ignores the disclosed property and returns an array of Doc objects of the active documents. During any other event, activeDocs returns an array of Doc objects of only those active documents that have disclosed set to true.

  • Beginning with Acrobat 7.0, execution of JavaScript through a menu event is no longer privileged. See Privileged context.

The array returned by app.activeDocs includes any documents opened by app.openDoc with the bHidden parameter set to true, subject to the security restrictions described above.

Example: This example searches among the open documents for the document with a title of myDoc, then inserts a button in that document using the Doc object addField method. Whether the documents must be disclosed depends on the version of Acrobat executing this code and on the placement of the code (for example, console versus mouse-up action).

var d = app.activeDocs;
for (var i=0; i < d.length; i++)
if (d[i].info.Title == "myDoc") {
    var f = d[i].addField("myButton", "button", 0, [20, 100, 100, 20]);
    f.setAction("MouseUp","app.beep(0)");
    f.fillColor=color.gray;99849106
}

calculate

    • Version (Key)

    • Save-Prefs

    • Security

    • Product

    • Type

    • Access

    • deprecated

    • No

    • No

    • All

    • Boolean

    • R/W

If true (the default value), calculations can be performed. If false, calculations are not permitted.

The use of this property is discouraged; the Doc object property calculate is preferred.

constants

Version (Key)

Save-Prefs

Security

Product

Type

Access

7.0

No

No

All

Object

R

A wrapper object for holding various constant values. Currently, this property returns an object with a single property, align.

app.constants.align is an object that has the possible properties left, center, right, top, and bottom, indicating the type of alignment. These values can be used to specify alignment, such as when adding a watermark.

Example: See the Doc object methods addWatermarkFromFile and addWatermarkFromText for examples.

focusRect

Version (Key)

Save-Prefs

Security

Product

Type

Access

4.05

P

No

All

Boolean

R/W

Turns the focus rectangle on and off. The focus rectangle is the faint dotted line around buttons, check boxes, radio buttons, and signatures to indicate that the form field has the keyboard focus. A value of true turns on the focus rectangle.

Example: Turn off the focus rectangle.

app.focusRect = false;

formsVersion

Version (Key)

Save-Prefs

Security

Product

Type

Access

4.0

No

No

All

Number

R

The version number of the viewer forms software. Check this property to determine whether objects, properties, or methods in newer versions of the software are available if you want to maintain backward compatibility in your scripts.

Example: Toggle fullscreen mode.

if (typeof app.formsVersion != "undefined" && app.formsVersion >= 5.0) {
        app.fs.defaultTransition = "";
        app.fs.isFullScreen = !app.fs.isFullScreen;
}
else app.fullscreen = !app.fullscreen;

fromPDFConverters

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

Array

R

An array of file type conversion ID strings. A conversion ID string can be passed to the Doc object saveAs method.

Example: List all currently supported conversion ID strings.

for ( var i = 0; i < app.fromPDFConverters.length; i++)
    console.println(app.fromPDFConverters[i]);

fs

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

No

No

All

Object

R

A FullScreen object, which can be used to access the fullscreen properties.

Example:

// This code puts the viewer into fullscreen (presentation) mode.
app.fs.isFullScreen = true;

See also fullScreenObject. isFullScreen.

fullscreen

    • Version (Key)

    • Save-Prefs

    • Security

    • Product

    • Type

    • Access

    • deprecated

    • No

    • No

    • All

    • Boolean

    • R/W

The use of this property is discouraged; it has been superseded by the FullScreen object property isFullScreen. The fs method returns a FullScreen object that can be used to access the fullscreen properties.

Controls whether the viewer is in full screen mode or regular viewing mode.

Note

A PDF document being viewed from within a web browser cannot be put into full screen mode. Full screen mode can be initiated from within the browser, but applies only to a document open in the Acrobat viewer application, if any, not to the browser itself.

language

Version (Key)

Save-Prefs

Security

Product

Type

Access

3.01

No

No

All

String

R

The language of the running Acrobat viewer. It can be one of the following strings.

String

Language

CHS

Chinese Simplified

CHT

Chinese Traditional

DAN

Danish

DEU

German

ENU

English

ESP

Spanish

FRA

French

ITA

Italian

KOR

Korean

JPN

Japanese

NLD

Dutch

NOR

Norwegian

PTB

Brazilian Portuguese

SUO

Finnish

SVE

Swedish

media

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

Object

R

Defines an extensive number of properties and methods useful for setting up and controlling a multimedia player.

See the app.media object for a listing of the properties and methods of this object, as well as numerous examples of use.

monitors

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

Monitors object

R

A Monitors object, which is an array containing one or more Monitor objects representing each of the display monitors connected to the user’s system. Each access to app.monitors returns a new, up-to-date copy of this array.

A Monitors object also has several methods that can be used to select a display monitor. Alternatively, JavaScript code can look through the array explicitly.

Example: Count the number of display monitors connected to the user’s system.

var monitors = app.monitors;
console.println("There are " + monitors.length
    + " monitor(s) connected to this system.");

numPlugIns

Version (Key)

Save-Prefs

Security

Product

Type

Access

deprecated

No

No

All

Number

R

Note

This method has been superseded by the plugIns property.

Indicates the number of plug-ins that have been loaded by Acrobat.

openInPlace

Version (Key)

Save-Prefs

Security

Product

Type

Access

4.0

P

No

All

Boolean

R/W

Specifies whether cross-document links are opened in the same window or opened in a new window.

Example: Open cross-document links in the same window.

app.openInPlace = true;

platform

Version (Key)

Save-Prefs

Security

Product

Type

Access

4.0

No

No

All

String

R

The platform that the script is currently executing on. There are three valid values:

WIN
MAC
UNIX

plugIns

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

No

No

All

Array

R

An array of PlugIn objects representing the plug-ins that are currently installed in the viewer.

Example:

// Get array of PlugIn objects
var aPlugins = app.plugIns;
// Get number of plug-ins
var nPlugins = aPlugins.length;
// Enumerate names of all plug-ins
for ( var i = 0; i < nPlugins; i++)
    console.println("Plugin #"+i+" is " + aPlugins[i].name);

printColorProfiles

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

Acrobat only

Array of Strings

R

A list of available printer color spaces. Each of these values is suitable to use as the value of the colorProfile property of a PrintParams object.

Example: Print out a listing of available printer color spaces:

var l = app.printColorProfiles.length
for ( var i = 0; i < l; i++)
    console.println("(" + (i+1) + ") " + app.printColorProfiles[i]);

printerNames

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

Array of Strings

R

A list of available printers. Each of these values is suitable to use in the printerName property of the PrintParams object. If no printers are installed on the system, an empty array is returned.

Example: Print out a listing of available printers:

var l = app.printerNames.length
for ( var i = 0; i < l; i++)
    console.println("(" + (i+1) + ") " + app.printerNames[i]);

runtimeHighlight

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

Acrobat Pro only

Boolean

R/W

If true, the background color and hover color for form fields are shown.

Example: If run-time highlighting is off (false), do nothing, otherwise change the preferences.

if (!app.runtimeHighlight)
{
    app.runtimeHighlight = true;
    app.runtimeHighlightColor = color.red;
}

runtimeHighlightColor

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

Acrobat Pro only

Color array

R/W

Sets the color for runtime highlighting of form fields.

The value of this property is a color array. (See Color arrays for details.)

Example: See the runtimeHighlight property.

thermometer

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

Object

R

A Thermometer object, which is a combined status window/progress bar that indicates to the user that a lengthy operation is in progress.

Example: See the Thermometer object.

toolbar

Version (Key)

Save-Prefs

Security

Product

Type

Access

3.01

No

No

Acrobat Pro only

Boolean

R/W

Allows a script to show or hide both the horizontal and vertical Acrobat toolbars of Acrobat 9 or earlier. In Acrobat X, allows a script to show or hide the Plugin Addon Tools panel on the right side of the display area. It does not hide the toolbar (Acrobat 9 or earlier) or the tools panel (Acrobat X), in external windows (that is, in an Acrobat window within a web browser).

Example: Hide the toolbar.

app.toolbar = false;

toolbarHorizontal

Version (Key)

Save-Prefs

Security

Product

Type

Access

deprecated

No

No

P

boolean

R/W

Note

This property has been deprecated in Acrobat 5.0 and later. If accessed, it acts like toolbar.

Allows a script to show or hide the Acrobat horizontal toolbar. It does not hide the toolbar in external windows (that is, in an Acrobat window within a web browser).

toolbarVertical

Version (Key)

Save-Prefs

Security

Product

Type

Access

deprecated

No

No

P

boolean

R/W

Note

This property has been deprecated in Acrobat 5.0 and later. If accessed, it acts like toolbar.

Allows a script to show or hide the Acrobat vertical toolbar. It does not hide the toolbar in external windows (that is, in an Acrobat window within a web browser).

viewerType

Version (Key)

Save-Prefs

Security

Product

Type

Access

3.01

No

No

All

String

R

A string that indicates which viewer application is running. It can be one of these values.

Value

Description

Reader

Acrobat Reader version 5.0 or earlier / Adobe Reader version 5.1 or later

Exchange

Adobe Acrobat earlier than version 6.0 / Acrobat Standard version 6.0 or later

Exchange-Pro

Acrobat Pro version 6.0 or later

viewerVariation

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

No

No

All

String

R

Indicates the packaging of the running viewer application. It can be one of these values:

Reader
Fill-In
Business Tools
Full

viewerVersion

Version (Key)

Save-Prefs

Security

Product

Type

Access

4.0

No

No

All

Number

R

Indicates the version number of the current viewer application.

app methods

addMenuItem

Version (Key)

Save-Prefs

Security

Product

5.0

No

Yes

All

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.

Parameters

Parameter

Description

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 Acrobat 6.0, the value of nPos can also be the language-independent name of a menu item. (Acrobat 6.0) If the value nPos is a string, this string is interpreted as a named item in the menu (a language-independent name of a menu item). The named item determines the position at which the new menu item is to be inserted. See bPrepend for additional details. The nPos parameter is ignored in certain menus that are alphabetized. The alphabetized menus are - The first section of View > Navigation Panels. - The first section of View > Toolbars. - 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. - Beginning with Acrobat 7.0, execution of JavaScript through a menu event is no longer privileged. See Privileged context.

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.

bPrepend

(optional, Acrobat 6.0) Determines the position of the new menu item relative to the position specified by nPos. The default value is false. If bPrepend is true, the rules for insertion are as follows: - If nPos is a string, the new item is placed before the named item. - If nPos is a number, the new item is placed before the numbered item. - If the named item cannot be found or nPos is not between zero and the number of items in the list, inclusive, the new item is inserted as the first item in the menu (rather than at the end of the menu). bPrepend is useful when the named item is the first item in a group.

Example 1: 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
});

Example 2 (Acrobat 6.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 });

addSubMenu

Version (Key)

Save-Prefs

Security

Product

5.0

No

Yes

All

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.

See also the addSubMenu, execMenuItem, hideMenuItem, and listMenuItems methods.

Parameter

Description

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 - The first section of View > Navigational Panels. - The first section of View > Toolbars. - 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.

Example: See the newDoc method.

addToolButton

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Adds a button to the “Add-on” toolbar of Acrobat 9 or earlier. In Acrobat X, adds a button to the Plugin Addon Tools panel on the right side of the display area.

If there is an active document (for example, docA.pdf) open in Acrobat when this method is called to add a button, Acrobat will remove the button when docA.pdf is either no longer active or is closed. In the former case, the button will be automatically added to the toolbar if docA.pdf becomes the active document again.

The icon size is restricted to 20 by 20 pixels. If an icon of larger dimensions is used, an exception is thrown.

Note

(Acrobat 7.0) A number of changes have been made with regard to the secure use of this method. Execution of addToolButton in the console and application initialization is considered privileged execution and is trusted.

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 context.)

See also removeToolButton.

Parameters

Parameter

Description

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). - 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 Acrobat 7.0, this parameter is optional if a cLabel is provided.

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. - 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, Acrobat 7.0) A text label to be displayed on the button to the right of the icon. The default is not to have a label.

Returns

undefined

Example: 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.

alert

Version (Key)

Save-Prefs

Security

Product

3.01

No

No

All

Displays an alert dialog box.

Parameters

Parameter

Description

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 - 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, Acrobat 6.0) The dialog box title. If not specified, the title “Adobe Acrobat” is used.

oDoc

(optional, Acrobat 6.0) The Doc object that the alert should be associated with.

oCheckbox

(optional, Acrobat 6.0) If specified, a check box is created in the lower left region of the alert box. oCheckbox is a generic JavaScript object that has three properties. The first two property values are passed to the alert method; the third property returns a Boolean value.

  • 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.

Returns

nButton, the type of the button that was pressed by the user:

  • 1: OK

  • 2: Cancel

  • 3: No

  • 4: Yes

Example 1: Display a simple alert box:

app.alert({
    cMsg: "Error! Try again!",
    cTitle: "Acme Testing Service"
});

Example 2: 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();

Example 3 (Acrobat 6.0)

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
    });
}

beep

Version (Key)

Save-Prefs

Security

Product

3.01

No

No

All

Causes the system to play a sound.

Note

On Mac OS and UNIX systems the beep type is ignored.

Parameters

Parameter

Description

nType

(optional) The sound type. Values are associated with sounds as follows:

  • 0: Error

  • 1: Warning

  • 2: Question

  • 3: Status

  • 4: Default (default value)

beginPriv

Version (Key)

Save-Prefs

Security

Product

7.0

No

Yes

All

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.

Returns

undefined on success, exception on failure

Example: For examples of usage, see trustedFunction and trustPropagatorFunction.

browseForDoc

Version (Key)

Save-Prefs

Security

Product

7.0

No

Yes

All

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 context.

Parameters

Parameter

Description

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.

Returns

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.

Example 1: 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.

Example 2: 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});

clearInterval

Version (Key)

Save-Prefs

Security

Product

5.0

No

No

All

Cancels a previously registered interval initially set by the setInterval method.

See also setTimeOut and clearTimeOut.

Parameters

oInterval

The registered interval to cancel.

Example: See setTimeOut.

clearTimeOut

Version (Key)

Save-Prefs

Security

Product

5.0

No

No

All

Cancels a previously registered time-out interval. Such an interval is initially set by setTimeOut.

See also setInterval and clearInterval.

Parameters

oTime

The previously registered time-out interval to cancel.

Example: See setTimeOut.

endPriv

Version (Key)

Save-Prefs

Security

Product

7.0

No

Yes

All

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.

Returns

undefined on success, exception on failure

Example: For examples of usage, see trustedFunction and trustPropagatorFunction.

execDialog

Version (Key)

Save-Prefs

Security

Product

7.0

No

No

All

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 Acrobat dialog boxes from those created by JavaScript, dialog boxes that are added at the document level have a title of “JavaScript Dialog” and display the text “Warning: JavaScript Dialog” at the bottom.

Parameters

Parameter

Description

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 Acrobat application.

Returns

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.

Dialog box handlers

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 example below.

"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 () { .. }

description property

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).

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. 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.

next_tab

String

An ItemID for the next dialog box item in the tab order. 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.

Additional attributes

Element type

Property

Type

Description

static_text

multiline

Boolean

If true, this static text element is multiline. 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.

edit_text

readonly

Boolean

If true, this text element is read only. This property is ignored when password is set to true.

edit_text

password

Boolean

If true, this text element is a password field.

edit_text

PopupEdit

Boolean

If true, it is a pop-up edit text element.

edit_text

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_cancel_other

ok_name

String

The name for the OK button.

ok, ok_cancel,| ok_cancel_other

cancel_name

String

The name for the cancel button.

ok, ok_cancel,| ok_cancel_other

other_name

String

The name for the other button.

Example 1: 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);

Example 2: 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:
                [
                    {
                        type: "static_text",
                        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.

Example 3: 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.

Example 4: 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 );

Example 5: See trustPropagatorFunction which shows how to execute privileged code from a non-privileged context.

execMenuItem

Version (Key)

Save-Prefs

Security

Product

4.0

No

Yes

All

Executes the specified menu item.

Beginning with Acrobat 5.0, app.execMenuItem("SaveAs") can be called, subject to the restrictions described below. Executing the Save As menu item saves the current file to the user’s hard drive after presenting a dialog box asking the user to select a folder and file name. The file is saved as a linearized file if “Save As Optimizes for Fast Web View” is checked in the Documents preferences.

Note

(Acrobat 7.0) In previous versions of Acrobat, the following code could only be executed during a batch, console or menu event.

app.execMenuItem("SaveAs");

Acrobat 7.0 removes this restriction, so that app.execMenuItem("SaveAs") can be executed during a mouse-up event, for example.

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 Acrobat 6.0, scripts are not allowed to execute the Paste menu item.

(Acrobat 8.0) The execution of menu items through execMenuItem method is restricted to a short list of safe menus. The execMenuItem method will silently fail if a named menu item is executed that is not on the safe menu list. Menu items may be removed in future releases, or their behavior may change .

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

Print

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_MACHINESOFTWAREPoliciesAdobeAdobe Acrobat9.0FeatureLockDowncDefaultExecMenuItems.

  • The key for the list used by Tuner is HKEY_LOCAL_MACHINESOFTWAREPoliciesAdobeAdobe Acrobat9.0FeatureLockDowncAdminExecMenuItems.

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.

Parameters

Parameter

Description

cMenuItem

The menu item to execute. A list of menu item names can be obtained with listMenuItems.

oDoc

(optional, Acrobat 7.0) oDoc is the Doc object of a document that is not hidden (see the Doc object hidden property). If this parameter is present, execMenuItem executes the menu item in the document’s context.

Example 1: This example executes the File > Open menu item. It displays a dialog box asking for the file to be opened.

app.execMenuItem("Open");

Example 2 (Acrobat 5.0)

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;

Example 3 (Acrobat 5.0)

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;

Example 4 (Acrobat 8.0 and later)

Execute app.execMenuItem in folder JavaScript using a trusted function.

myTrustedMenu = app.trustedFunction( function( name )
{
    app.beginPriv();
    app.execMenuItem(name);
    app.endPriv();
});

Once Acrobat or Adobe Reader is restarted, the script, for example,

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.

getNthPlugInName

Version (Key)

Save-Prefs

Security

Product

deprecated

No

No

All

Note

This method has been superseded by the plugIns property.

Obtains the name of the n th plug-in that has been loaded by the viewer.

Parameters

nIndex

The n th plug-in loaded by the viewer.

Returns

cName, the plug-in name that corresponds to nIndex.

getPath

Version (Key)

Save-Prefs

Security

Product

6.0

No

Yes

All

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

(Acrobat 7.0) This method can only be executed during a batch or console event (see the event object). See also Privileged context.

Parameters

Parameter

Description

cCategory

(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, javascript, stamps, dictionaries, plugIns spPlugIns,help, temp, messages, resource, update The default is root.

Returns

The path to the folder determined by the parameters. An exception is thrown if the folder does not exist.

Example 1: 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);

Example 2: 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();

goBack

Version (Key)

Save-Prefs

Security

Product

3.01

No

No

All

Goes to the previous view on the view stack, which is equivalent to clicking the Previous View button on the Acrobat toolbar.

Example: 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

goForward

Version (Key)

Save-Prefs

Security

Product

3.01

No

No

All

Goes to the next view on the view stack, which is equivalent to clicking the go Next View button on the Acrobat toolbar.

Example: See the example following app. goBack.

hideMenuItem

Version (Key)

Save-Prefs

Security

Product

4.0

No

Yes

All

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.

Parameters

Parameter

Description

cName

The menu item name to remove. Menu item names can be discovered with listMenuItems.

hideToolbarButton

Version (Key)

Save-Prefs

Security

Product

4.0

No

Yes

All

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.

Parameters

Parameter

Description

cName

The name of the toolbar button to remove. Toolbar item names can be discovered with listToolbarButtons.

Example: 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.

launchURL

Version (Key)

Save-Prefs

Security

Product

7.0

No

Yes

All

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.

Parameters

Parameter

Description

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.

Returns

The value undefined is returned on success. An exception is thrown on failure.

Example 1:

app.launchURL("http://www.example.com/", true);

Example 2: 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.

listMenuItems

Version (Key)

Save-Prefs

Security

Product

5.0

No

No

All

Beginning with Acrobat 6.0, returns an array of TreeItem objects, which describes a menu hierarchy.

Prior to Acrobat 6.0, this method returned a list of menu item names to the console.

See also addMenuItem, addSubMenu, execMenuItem, and hideMenuItem.

Returns

Array of TreeItem objects.

TreeItem Object

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 Acrobat 6.0). It contains the following properties.

cName

The name of a menu item or toolbar button.

oChildren

(optional) An array of treeItem objects containing the submenus or flyout buttons.

Example 1: List all menu item names to the console.

var menuItems = app.listMenuItems()
for( var i in menuItems)
    console.println(menuItems[i] + "n")

Example 2: 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);

listToolbarButtons

Version (Key)

Save-Prefs

Security

Product

5.0

No

No

All

Beginning with Acrobat 6.0, returns an array of treeItem objects that describes a toolbar hierarchy (with flyout toolbars).

Prior to Acrobat 6.0, this method displayed a list of toolbar button names in the console.

(Acrobat 8.0) In the Documents category of the Preferences dialog box, when “Show each document in its own window (requires restart)” item is checked, the document window must be empty in order for listToolbarButtons to return the array of TreeItem objects.

Returns

Array of TreeItem objects

Example: 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.

loadPolicyFile

    • Version (Key)

    • Save-Prefs

    • Security

    • Product

    • 9.0

    • No

    • No

    • All

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.

Parameters

Parameter

Description

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. - 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.

Returns

Nothing

mailGetAddrs

Version (Key)

Save-Prefs

Security

Product

6.0

No

Yes

Not available in Reader

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

(Acrobat 7.0) This method can only be executed during a batch or console event. See also Privileged context. See the event object for a discussion of JavaScript events.

Parameters

Parameter

Description

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).

Returns

On failure (the user cancelled), returns undefined. On success, returns an array of three strings for To, CC, and BCC.

Example: 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
}

mailMsg

Version (Key)

Save-Prefs

Security

Product

4.0

No

Yes

All

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.

Parameters

Parameter

Description

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. - (Acrobat 7.0) When this method is executed in a non-privileged context, the bUI parameter is not honored and defaults to true. See Privileged context.

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.

Example: 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:nn";
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
} );

newDoc

Version (Key)

Save-Prefs

Security

Product

5.0

No

Yes

Not available in Reader

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 context. See the event object for a discussion of JavaScript events.

Parameters

Parameter

Description

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.

Returns

The object of the newly created document.

Example: Add a New item to the Acrobat File menu. Within New, there are three menu items: Letter, A4, and Custom. This script should go in a folder-level JavaScripts .js file.

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 Acrobat prior to 7.0. For Acrobat 7.0, it works correctly if the user JavaScript preference Enable Menu Items JavaScript Execution Privileges is enabled.

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 Acrobat 7.0. See Privileged context.

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 PDF Reference for the current limitations.

Example: 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.

newCollection

Version (Key)

Save-Prefs

Security

Product

9.0

No

No

All

Creates a new collection-based PDF, a PDF portfolio, with no content.

To work with an existent PDF portfolio, begin with Doc. collection.

Returns

A Doc object of the newly created PDF.

Example: Create a new PDF portfolio and get the Doc object of the newly created PDF.

var doc = app.newCollection();

newFDF

Version (Key)

Save-Prefs

Security

Product

6.0

No

Yes

Not available in Reader

Creates a new FDF object that contains no data.

Note

This method is available only during batch, console and application initialization. Not available in Adobe Reader. See Privileged context.

Returns

A new FDF object.

Example: 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.

openDoc

Version (Key)

Save-Prefs

Security

Product

5.0

No

No

All

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.

Parameters

Parameter

Description

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. - 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, Acrobat 7.0) A string that specifies the source file system name. Two values are supported: “” (the empty string, which is the default), representing the default file system, and “CHTTP”. This parameter is relevant only if the web server supports WebDAV.

bHidden

(optional, Acrobat 7.0) A Boolean value that if true, opens the PDF file with its window hidden. The default is false.

bUseConv

(optional, Acrobat 7.0) A Boolean value that is used when cPath references a non-PDF file. If true, the method tries to convert the non-PDF file to a PDF document. The default is false. - (Acrobat 7.0) bUseConv can only be set to true during a console or batch event. See also Privileged context.

cDest

(optional, Acrobat 8.0) The name of the destination within a document. This parameter forces opening at named destination within the PDF document. For details on named destinations and how to create them, see the PDF Reference.

Returns

A Doc object or null :

  • In Acrobat 5.0, this method returns a Doc object.

  • In Acrobat 5.0.5, the method returns the Doc object unless the disclosed property of the target document is not true, in which case it returns null.

  • Beginning with the Acrobat 5.0.5 Accessibility and Forms Patch and continuing with Acrobat 6.0 and later, openDoc behaves as follows:

    • 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.

Example 1: 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.

Example 2: Open an HTML document on the user’s hard drive and convert it to PDF.

try {
    app.openDoc("/c/myWeb/myHomePage.html");
} catch (e) {};

Example 3 (Acrobat 7.0)

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();

Example 4 (Acrobat 7.0)

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
})

Example 5 (Acrobat 7.0)

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.

Example 6 (Acrobat 8.0)

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.

openFDF

Version (Key)

Save-Prefs

Security

Product

6.0

No

Yes

Not available in Reader

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 context.

Parameters

cDIPath

The device-independent path to the file to be opened.

Returns

The FDF object for the FDF file that is opened.

Example: 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.

popUpMenu

Version (Key)

Save-Prefs

Security

Product

5.0

No

No

All

Note

popUpMenuEx is preferred over this method.

Creates a pop-up menu at the current mouse position, containing the specified items.

Parameters

Parameter

Description

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.

Returns

The name of the menu item that was selected, or null if no item was selected.

Example: 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");

popUpMenuEx

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

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.

Parameters

One or more MenuItem objects (see below).

Returns

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.

MenuItem Object

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.

Example 1: 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");

Example 2: 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);

removeToolButton

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Removes a previously added button from the toolbar.

Note

(Acrobat 7.0) To remove a toolbutton added by the addToolButton method, removeToolButton must be executed within the same context as when addToolButton was executed.

If no document was open in Acrobat when the button was added, there must be no document open in Acrobat when the button is removed. See example 2 below.

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.

Parameters

Parameter

Description

cName

The language-independent identifier provided when addToolButton was called.

Example 1: See the example following addToolButton.

Example 2: This example shows the removal of a toolbutton with the same context as addToolButton. Initially, there is no document open in the Acrobat. Execute the following code from the console:

app.addToolButton({cName: "button1", cExec:"app.alert('pressed');",

     cTooltext:"Button1"});

Open a PDF document in Acrobat and execute the next line from the console:

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.

response

Version (Key)

Save-Prefs

Security

Product

3.01

No

No

All

Displays a dialog box containing a question and an entry field for the user to reply to the question.

Parameters

Parameter

Description

cQuestion

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, Acrobat 6.0) A short string to appear in front of and on the same line as the edit text field.

Returns

A string containing the user’s response. If the user clicks the Cancel button, the response is the null object.

Example: 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);

setInterval

Version (Key)

Save-Prefs

Security

Product

5.0

No

No

All

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 Acrobat 7.05, an interval is automatically terminated when the document whose script called setInterval is closed (assuming it was not previously terminated).

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.

Parameters

cExpr

The JavaScript script to be executed.

nMilliseconds

The time period in milliseconds.

Returns

An interval object

Example: 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.

setTimeOut

Version (Key)

Save-Prefs

Security

Product

5.0

No

No

All

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 Acrobat 7.05, an interval is automatically terminated when the document whose script called setInterval is closed (assuming it was not previously terminated).

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.

Parameters

cExpr

The JavaScript script to be executed.

nMilliseconds

The time period in milliseconds.

Returns

A timeout object

Example: Create a simple running marquee. Assume there is a text field named “marquee”. The default value of this field is “Adobe Acrobat version 8.0 will soon be here!”.

// 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.

trustedFunction

Version (Key)

Save-Prefs

Security

Product

7.0

No

No

All

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 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

Parameters

Parameter

Description

oFunc

A function object that specifies the function to mark as trusted.

Returns

On success, returns the same function object that was passed in. After successful execution, the function object will be trusted. On error, throws NotAllowedError.

Syntax

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.

Example 1: 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 Acrobat is restarted, the trustedNewDoc function can be executed from anywhere. The following script for a mouse-up action of a button creates a new document that is 200 points by 200 points.

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.

Example 2: 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.

Example 3: 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).

trustPropagatorFunction

Version (Key)

Save-Prefs

Security

Product

7.0

No

Yes

All

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.

Syntax

This method can be called in two ways.

myPropagatorFunction = app.trustPropagatorFunction(
    function()
    {
        <function body>
    }
);

or

function myOtherPropagatorFunction()
{
    <function body>
};
app.trustPropagatorFunction(myOtherPropagatorFunction);

Parameters

Parameter

Description

oFunc

A function object that specifies the function to mark as a trust propagator.

Returns

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.

Example 1: 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");

Example 2: 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 } );

app.media

This object defines properties and functions useful in multimedia JavaScript code.

Several app.media properties are enumeration objects that list the values allowed in various properties. Future versions of Acrobat may add more such values, and JavaScript code should be prepared to encounter values other than the ones listed here. Similarly, JavaScript code may be run on an older version of Acrobat than it was designed for, in which case it must fall back to using the values available in that version.

Note

The app.media is part of the Acrobat 6.0 (and Later) Compatible Media JavaScript API. Multimedia assets that use this approach rely on the underlying operating system to locate and launch a multimedia player residing on the user’s system. Acrobat 9.0 natively supports Flash video (FLV) and Flash applications (SWF) which can be embedded in, or streamed to, a PDF document. Native support for Flash enables reliable cross-platform playback. No additional media player or specific codec is necessary.

Acrobat 6.0 (and Later) Compatible Media is superseded by the multimedia of Acrobat 9.0, which uses rich media annotations. Developers of PDFs with multimedia assets are, therefore, strongly encouraged to use the rich media annotations of Acrobat 9. Refer to the AnnotRichMedia object for JavaScript support for rich media annotations.

app.media properties

align

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

Object (enumeration)

R

Enumerates the values that may be found in the MediaSettings.floating.align property. The alignment is relative to the window specified by the MediaSettings.floating.over property. (See the values for app.media. over.)

Valid values are listed in the table below.

Value

Position of floating window

app.media.align.topLeft

At the top left corner

app.media.align.topCenter

At the top center

app.media.align.topRight

At the top right corner

app.media.align.centerLeft

At the center left

app.media.align.center

At the center

app.media.align.centerRight

At the center right

app.media.align.bottomLeft

At the bottom left corner

app.media.align.bottomCenter

At the bottom center

app.media.align.bottomRight

At the bottom right corner

canResize

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

Object (enumeration)

R

Enumerates the values that may be found in the MediaSettings.floating.canResize property, which specifies whether a floating window may be resized by the user.

These values are listed in the table below.

Value

Description

app.media.canResize.no

May not be resized

app.media.canResize.keepRatio

May be resized only if the aspect ratio is preserved

app.media.canResize.yes

May be resized without preserving the aspect ratio

closeReason

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

Object (enumeration)

R

Enumerates the values that may be found in the event.reason property for a Close event. These values are:

  • app.media.closeReason.general

  • app.media.closeReason.error

  • app.media.closeReason.done

  • app.media.closeReason.stop

  • app.media.closeReason.play

  • app.media.closeReason.uiGeneral

  • app.media.closeReason.uiScreen

  • app.media.closeReason.uiEdit

  • app.media.closeReason.docClose

  • app.media.closeReason.docSave

  • app.media.closeReason.docChange

See the afterClose and onClose methods of the EventListener object.

defaultVisible

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

Boolean

R

This property is defined as true, which is the default value for MediaSettings.visible.

ifOffScreen

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

Object (enumeration)

R

Enumerates the values allowed in a MediaSettings.floating.ifOffScreen property, which specifies what action should be taken if the floating window is positioned totally or partially offscreen.

These values and their descriptions are given in the table below.

Value

Description

app.media.ifOffScreen.allow

Take no action

app.media.ifOffScreen.forceOnScreen

Move and/or resize the window so that it is on-screen

app.media.ifOffScreen.cancel

Cancel playing the media clip

layout

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

Object (enumeration)

R

Enumerates the values allowed in a MediaSettings.layout property.

The table below contains the values and their descriptions.

Value

Description

app.media.layout.meet

Scale to fit all content, preserve aspect, no clipping, background fill

app.media.layout.slice

Scale to fill the window, preserve aspect, and clip X or Y as needed

app.media.layout.fill

Scale X and Y separately to fill the window

app.media.layout.scroll

Natural size with scrolling

app.media.layout.hidden

Natural size with clipping

app.media.layout.standard

Use the player’s default settings

monitorType

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

Object (enumeration)

R

Enumerates the values allowed in a MediaSettings.monitorType property.

The table below contains the values and their descriptions:

Value

Description

app.media.monitorType.document

The monitor containing the largest section of the document window

app.media.monitorType.nonDocument

The monitor containing the smallest section of the document window

app.media.monitorType.primary

Primary monitor

app.media.monitorType.bestColor

Monitor with the greatest color depth

app.media.monitorType.largest

Monitor with the greatest area (in pixels squared)

app.media.monitorType.tallest

Monitor with the greatest height (in pixels)

app.media.monitorType.widest

Monitor with the greatest width (in pixels)

openCode

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

Object (enumeration)

R

Enumerates the values that may be found in the code property of the return value from MediaPlayer.open. The values are:

  • app.media.openCode.success

  • app.media.openCode.failGeneral

  • app.media.openCode.failSecurityWindow

  • app.media.openCode.failPlayerMixed

  • app.media.openCode.failPlayerSecurityPrompt

  • app.media.openCode.failPlayerNotFound

  • app.media.openCode.failPlayerMimeType

  • app.media.openCode.failPlayerSecurity

  • app.media.openCode.failPlayerData

over

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

Object (enumeration)

R

Enumerates the values allowed in a MediaSettings.floating.over property, the value of which is used to align a floating window. See app.media.align.

Value

Description

app.media.over.pageWindow

Align the floating window relative to the document (page) window

app.media.over.appWindow

Align the floating window relative to the application window

app.media.over.desktop

Align the floating window relative to the full virtual desktop

app.media.over.monitor

Align the floating window relative to the (selected) monitor display screen

pageEventNames

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

Object (enumeration)

R

Enumerates the values that may be found in the event.name property for a page-level action. Event names that represent direct user actions are not included here. This enumeration is used to distinguish page-level actions from user actions. The values are:

  • app.media.pageEventNames.Open

  • app.media.pageEventNames.Close

  • app.media.pageEventNames.InView

  • app.media.pageEventNames.OutView

Example: app.media.pageEventNames can be used to distinguish between a page-level action and a direct user action. The script below is folder-level or document-level JavaScript that can be called from anywhere in a document.

function myMMfunction () {
    if ( app.media.pageEventNames[event.name] ) {
        console.println("Page Event: " + event.name);
        ...
    } else {
        console.println("User Generated Event: " + event.name);
        ...
    }
}

raiseCode

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

Object (enumeration)

R

Enumerates values that may be found in the error.raiseCode property when an exception is thrown. This property exists only when error.name is “RaiseError”. Other values may be encountered in addition to these.

app.media.raiseCode.fileNotFound
app.media.raiseCode.fileOpenFailed

raiseSystem

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

Object (enumeration)

R

Enumerates values that may be found in the error.raiseSystem property when an exception is thrown. This property exists only when error.name is “RaiseError”.

app.media.raiseSystem.fileError

Other values may be added to the above property.

renditionType

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

Object (enumeration)

R

Enumerates the values that may be found in Rendition.type. The values and their descriptions are given below.

Value

Description

app.media.renditionType.unknown

A type not known by this version of Acrobat

app.media.renditionType.media

A media rendition

app.media.renditionType.selector

A rendition selector

status

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

Object (enumeration)

R

Enumerates the values that may be found in the event.media.code property for a Status event (see onStatus and afterStatus). Most of these values have additional information that is found in the event.text property. The values are:

Value

Description

app.media.status.clear

Empty string—this status event clears any message

app.media.status.message

General message

app.media.status.contacting

Hostname being contacted

app.media.status.buffering

Progress message or nothing

app.media.status.init

Name of the engine being initialized

app.media.status.seeking

Empty string

Along with the event.media.status code, there is also the event.media.text, a string that reflects the current status, as described above.

trace

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

Boolean

R/W

Set this property to true to print trace messages to the JavaScript console during player creation and event dispatching.

Note

app.media.trace is for test purposes only. Do not use this property in a PDF file that you publish. It will change in future versions of Acrobat.

version

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

Number

R

The version number of the multimedia API, currently 7.0.

windowType

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

Object (enumeration)

R

Enumerates the values allowed in a MediaSettings.windowType property. These values are given in the table below.

Value

Description

app.media.windowType.docked

Docked to a PDF page

app.media.windowType.floating

Floating (pop-up) window

app.media.windowType.fullScreen

Full screen mode

app.media methods

addStockEvents

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Adds stock EventListeners to a MediaPlayer object and sets player.stockEvents as a reference to these listeners for later removal.

If the optional annot parameter is provided, a reference to the annotation is saved in MediaPlayer.annot. Later, when the player is opened with MediaPlayer.open, stock EventListeners will also be added to this annotation and annot.player will be set as a reference to the player.

Parameters

player

A required MediaPlayer object

annot

(optional) A ScreenAnnot object

The stock EventListeners provide standard Acrobat behavior such as focus handling.

If app.media.trace is true, debug trace listeners are also included with the stock EventListeners.

Use the removeStockEvents method to remove EventListeners that were added with addStockEvents.

The app.media.createPlayer and app.media.openPlayer methods call addStockEvents internally, so in most cases it is not necessary to call this method yourself.

alertFileNotFound

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Displays the standard file not found alert, with an optional Don’t Show Again check box.

Parameters

Parameter

Description

oDoc

oDoc is the Doc the alert is associated with

cFilename

cFilename is the name of the missing file

bCanSkipAlert

(optional) If bCanSkipAlert is true and the user checks the check box, returns true, otherwise returns false. The default is false.

Returns

If bCanSkipAlert is true, returns true if the check box is checked, otherwise returns false.

Example:

if ( !doNotNotify )
{
    var bRetn = app.media.alertFileNotFound(this, cFileClip, true );
    var doNotNotify = bRetn;
}

alertSelectFailed

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Displays the standard alert for a rendition.select failure.

Parameters

Parameter

Description

oDoc

The Doc the alert is associated with

oRejects

(optional) If provided, an array of MediaReject objects as returned by PlayerInfoList.select.

bCanSkipAlert

(optional) If true and the user checks the check box, the method returns true ; otherwise, the method returns false. The default is false.

bFromUser

(optional) A Boolean value that affects the wording of the alert message. It should be true if a direct user action triggered this code, or false if some other action, such as selecting a bookmark, triggered it. The default is false.

Returns

If bCanSkipAlert is true, returns true if the check box is checked, otherwise returns false.

Note

When rendition.select fails to find a usable player, and the select parameter bWantRejects is set to true, the returned MediaSelection object will contain an array of MediaReject objects, which can be passed to this method as the oRejects parameter. The alertSelectFailed method will, in turn, ask the user to go to the web to download an appropriate player.

Example: Displays Cannot Play Media Clip, with check box.

var bRetn = app.media.alertSelectFailed({
    oDoc: this,
    bCanSkipAlert: true
});

argsDWIM

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

This method is a “do what I mean” function that is used by app.media.createPlayer, app.media.openPlayer, and app.media.startPlayer. It fills in default values for properties that are not provided in the PlayerArgs object, picking them out of the event object, so that these functions may be used as rendition action event handlers with no arguments or in custom JavaScript with explicit arguments.

Parameters

Parameter

Description

args

A PlayerArgs object (see app.media. createPlayer).

Returns

PlayerArgs object

Example: See createPlayer for an example of usage.

canPlayOrAlert

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Determines whether any media playback is allowed and returns true if it is. If playback is not allowed, it alerts the user and returns false.

Parameters

Parameter

Description

args

A PlayerArgs object (see app.media. createPlayer).

Returns

true if media playback is allowed, otherwise false.

Note

The createPlayer method calls this function before attempting to create a player. If you write your own code to substitute for createPlayer, you can call canPlayOrAlert to alert the user in situations where playback is not allowed, such as in multimedia authoring mode.

The only property in the args object that is used is doc, so you can use the following code.

// There is a Doc in myDoc
if( app.media.canPlayOrAlert({ doc: myDoc })
/* OK to create player here */ ;

The above code displays “Cannot play media while in authoring mode”, or other alerts, as appropriate.

computeFloatWinRect

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Calculates and returns the rectangle in screen coordinates needed as specified by its parameters.

Parameters

Parameter

Description

doc

The Doc object for the document.

floating

The floating parameters from the object returned by MediaSettings.floating.

monitorType

A number indicating which monitor to use. See the app.media. monitorType property.

uiSize

(optional) The user interface size given as an array of four numbers [w, x, y, z] representing the size, as returned by MediaPlayer.uiSize.

Returns

The rectangle in screen coordinates.

Example: Get the calculated rectangle for a floating window.

var floating =
{
    over: app.media.over.monitor,
    align: app.media.align.center,
    canResize: app.media.canResize.no,
    hasClose: false,
    hasTitle: true,
    width: 400,
    height: 400
}
var rect = app.media.computeFloatWinRect
    (this, floating, app.media.monitorType.primary);

constrainRectToScreen

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Returns a rectangle of screen coordinates, moved and resized if needed to place it entirely on some display monitor. If anchorPt is provided and rect must be shrunk to fit, it shrinks proportionally toward anchorPt (which is an array of two numbers representing a point as [x, y]).

Parameters

Parameter

Description

rect

An array of four numbers representing the screen coordinates of the d rectangle.

anchorPt

(optional) An array of two points [x, y] that is to be an anchor point.

Returns

A rectangle in screen coordinates.

createPlayer

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Creates a MediaPlayer object without opening the player.

Note

To open the player, call MediaPlayer.open. You can combine these two steps into one by calling app.media.openPlayer instead of createPlayer.

If createPlayer is called inside a rendition action (for example, in custom JavaScript entered from the Actions tab in the Multimedia Properties panel), default values are taken from the action’s event object. The args parameter is not required in this case unless you want to override the rendition action’s values. createPlayer calls argsDWIM to process the event object and args (see PlayerArgs object object) parameter.

Unless noStockEvents of the PlayerArgs object is set to true, the MediaPlayer object is equipped with stock EventListeners that provide the standard behavior required to interact properly with Acrobat. Additional EventListeners can be provided in the PlayerArgs object or may be added afterward with MediaPlayer.events.add.

If args.annot.player is an open MediaPlayer, createPlayer closes that player, which triggers events.

Parameters

Parameter

Description

args

A PlayerArgs object, whose required and optional properties are described below. If createPlayer is executed within a Rendition action with an associated rendition, this parameter is optional and its properties are populated by the defaults and by options selected in the UI. Otherwise, this parameter is required.

PlayerArgs object

Property

Type

Description

doc

Object

The Doc object of the document. Required if both annot and rendition are omitted, for example, for URL playback.

annot

Object

A ScreenAnnot object. Required for docked playback unless it is found in the event object or MediaSettings.page is provided. The new player is associated with the annotation. If a player was already associated with the annotation, it is stopped and closed.

rendition

Object

(optional) A Rendition object (either a MediaRendition or a RenditionList). Required unless rendition is found in the event object or URL is present.

URL

String

Either URL or rendition is required, with URL taking precedence.

mimeType

String

(optional) Ignored unless URL is present. If URL is present, either mimeType or settings.players, as returned by app.media.getPlayers, is required.

settings

Object

(optional) A MediaSettings object. Overrides the rendition settings.

events

Object

(optional) An EventListener object. Optional if stock events are used, added after stock events.

noStockEvents

Boolean

(optional) If true, do not use stock events. The default is false.

fromUser

Boolean

(optional) It should be true if a direct user action will trigger this code, or false, otherwise. The default depends on the event object.

showAltText

Boolean

(optional) If true, show alternate text (see Rendition. altText ) if the media cannot be played. The default is true.

showEmptyAltText

Boolean

(optional) If true and alternate text (see Rendition. altText ) is empty, show the alternate text as an empty box; if false, respond with an alert.

The default value is true if fromUser is false, and false if fromUser is true.

Returns

MediaPlayer object

Example 1: The following code is the definition of openPlayer, which uses createPlayer in its definition.

app.media.openPlayer = function( args )
{
    var player = null;
    try
    {
        args = app.media.argsDWIM( args );

        player = app.media.createPlayer( args );
        if( player )
        {
            var result = player.open();
            if( result.code != app.media.openCode.success )
            {
                player = null;
                app.media.alert
                    ( "Open", args, { code: result.code } );
            }
            else if( player.visible )
            player.setFocus();  // triggers Focus event
        }
    }
    catch( e )
    {
        player = null;
        app.media.alert( 'Exception', args, { error: e } );
    }

    return player;
}

Example 2: See the examples at the end of the description of openPlayer for examples of PlayerArgs usage.

getAltTextData

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Returns a MediaData object (see MediaSettings. data) that represents alternate text data for the given text. This object can be used to create a player to display the alternate text.

Parameters

cAltText

A string that is to be used as alternate text data.

Returns

  • MediaData object (see MediaSettings. data).

Example: See the embedded example following the getAltTextSettings method.

getAltTextSettings

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Takes a PlayerArgs object containing at least settings, showAltText, and showEmptyAltText properties, along with a selection object as returned by rendition.select, and finds the first available alternate text rendition if there is one. It then creates and returns a new MediaSettings object suitable for playback of the alternate text. Otherwise it returns null.

Parameters

args

A PlayerArgs object

selection

A MediaSelection object

Returns

MediaSettings object or null

Example: This example plays back the alternate text of the rendition. The code plays back the alternate text in a screen annotation, but can be modified for playback in a floating window.

var rendition = this.media.getRendition("myClip");
var settings = rendition.getPlaySettings();
var args = {
    settings: settings,
    showAltText: true,
    showEmptyAltText: true
};
var selection = rendition.select();
settings = app.media.getAltTextSettings( args, selection );

// You can also play custom alternate text by uncommenting the next line
// settings.data = app.media.getAltTextData("A. C. Robat");

// Uncomment the code below to obtain a floating window to play back
// the alternate text
/*
settings.windowType = app.media.windowType.floating
settings.floating = {
    canResize: app.media.canResize.keepRatio,
    hasClose: true,
    width: 400,
    height: 100
} */

// Now define an args parameter for use with openPlayer, which will

 // play the alternate text.
args = {
    rendition: rendition,
    annot: this.media.getAnnot({nPage: 0, cAnnotTitle:"myScreen"}),
    settings: settings
};
app.media.openPlayer(args);

getAnnotStockEvents

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Returns an event object containing the stock EventListeners required in a screen annotation for normal playback in Acrobat. The stock EventListeners provide standard Acrobat behavior such as focus handling.

If app.media.trace is true, debug trace listeners are also included with the stock EventListeners.

Parameters

Parameter

Description

settings

A number corresponding to the window type (see app.media.windowType).

Returns

event object

getAnnotTraceEvents

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Returns an Events object containing EventListeners that provide a debugging trace as events are dispatched.

Returns

Events object

getPlayers

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Returns a PlayerInfoList object, which is an array of PlayerInfo objects representing the available media players.

The PlayerInfoList may be filtered using its select method, and it may be used in the settings.players property when creating a media player with createPlayer.

See PlayerInfoList object and PlayerInfo object for more details.

Parameters

Parameter

Description

cMimeType

(optional) An optional MIME type such as “audio/wav”. If cMimeType is omitted, the list includes all available players. If cMimeType is specified, the list includes only players that can handle that MIME type.

Returns

PlayerInfoList object

Example 1: List MP3 players to the debug console.

var mp = app.media.getPlayers("audio/mp3")
for ( var i = 0; i < mp.length; i++) {
    console.println("nmp[" + i + "] Properties");
    for ( var p in mp[i] ) console.println(p + ": " + mp[i][p]);
}

Example 2: Choose any player that can play Flash media by matching the MIME type. The code assumes the code below is executed as a Rendition action with associated rendition (so no arguments for createPlayer are required).

var player = app.media.createPlayer();
player.settings.players
    = app.media.getPlayers( "application/x-shockwave-flash" );
player.open();

getPlayerStockEvents

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Returns an Events object containing the stock EventListeners required in a media player for normal playback in Acrobat. The stock EventListeners provide standard Acrobat behavior such as focus handling.

Use MediaPlayer.events.add to add these stock events to a media player.

The app.media.createPlayer and app.media.openPlayer methods automatically call getPlayerStockEvents internally, so it is not necessary to call this method yourself unless you are writing code that sets up all EventListeners explicitly.

If app.media.trace is true, debug trace listeners are also included with the stock EventListeners.

Parameters

settings

A MediaSettings object.

Returns

Events object

getPlayerTraceEvents

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Returns an Events object containing EventListeners that provide a debugging trace as events are dispatched.

Returns

An Events object

getRenditionSettings

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Calls Rendition.select to get a MediaSelection object, then MediaSelection.rendition.getPlaySettings to get a MediaSettings object for playback. If either of these fails, it calls the getAltTextSettings method to get a MediaSettings object for alternate text playback. Finally, it returns the resulting MediaSettings object, or null if getAltTextSettings returned null (that is, alternate text was not specified or not allowed).

Parameters

args

A PlayerArgs object.

Returns

MediaSettings object or null

Example: See example 3 following openPlayer.

getURLData

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Returns a MediaData object (see MediaSettings. data) that represents data to be retrieved for a URL and optional MIME type. This MediaData object can be used to create a player that accesses data from that URL.

Parameters

cURL

The URL from which media data is to be retrieved.

cMimeType

(optional) The MIME type of the data.

Returns

MediaData object

Example: Retrieve a media clip from the Internet and plays it in a floating window.

var myURLClip = "http://www.example.com/myClip.mpg";
var args = {
    URL: myURLClip,
    mimeType: "video/x-mpg",
    doc: this,
    settings: {
        players: app.media.getPlayers("video/x-mpg"),
        windowType: app.media.windowType.floating,
        data: app.media.getURLData(myURLClip,"video/x-mpg"),
        floating: { height: 400, width: 600 }
    }
}
app.media.openPlayer(args);

getURLSettings

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Takes a PlayerArgs object that contains a settings property and returns a MediaSettings object suitable for playback of a URL. The settings property must contain a URL property and may contain a mimeType property. It may also contain additional settings that are copied into the resulting settings object.

Parameters

args

A PlayerArgs object.

Returns

MediaSettings object

Example 1: Same example as above. getURLSettings calls getURLData and inserts the return MediaData object into the data property into the setting, which it then returns.

var myURLClip = "http://www.example.com/myClip.mpg";
args = {
    URL: myURLClip,
    mimeType: "video/x-mpg",
    doc: this,
    settings:
    {
        players: app.media.getPlayers("video/x-mpg"),
        windowType: app.media.windowType.floating,
        floating: { height: 400, width: 600 }
    }
};
settings = app.media.getURLSettings(args)
args.settings = settings;
app.media.openPlayer(args);

Example 2: The example below is a custom keystroke action of a combo box. The combo box is a simple playlist of streamed audio and video websites. The export value of each element in the list has the form “URL,mimeType”, for example

http://www.example.com/streaming/radio.asx,video/x-ms-asx

The script below splits the export value into a 2-element array, where the first element is the URL and the second is the mimeType. Any video is shown in the screen annotation “myScreen”. Otherwise, only audio is heard.

if (!event.willCommit)
{
    var aURLMime = event.changeEx.split(",")
    console.println("aURLMime[0] = " + aURLMime[0]);
    console.println("aURLMime[1] = " + aURLMime[1]);
    var args = {
        annot:this.media.getAnnot({ nPage:0,cAnnotTitle: "myScreen" }),
        URL: aURLMime[0],
        mimeType: aURLMime[1],
        doc: this,
        settings: {
            players: app.media.getPlayers(aURLMime[1]),
            windowType: app.media.windowType.docked
        }
    };
    settings = app.media.getURLSettings(args);
    args.settings = settings;
    var player = app.media.openPlayer(args);
}

getWindowBorderSize

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Returns an array of four numbers representing the size in pixels of the left, top, right, and bottom borders that would be used for a floating window with the properties specified in the parameters.

The hasTitle and hasClose parameters are Boolean values, and canResize may be any of the values in app.media.canResize.

These parameters have the same names as properties of a MediaSettings.floating object, so you can simply pass in a floating object as a single parameter:

var size = doc.media.getWindowBorderSize( settings.floating );

Parameters

hasTitle

(optional) The default is true.

hasClose

(optional) The default is true.

canResize

(optional) The default is app.media.canResize.no.

Returns

An array of 4 numbers.

openPlayer

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Calls app.media.createPlayer to create a MediaPlayer object and then calls MediaPlayer.open to open the player.

This method triggers several events, which may include Ready (see onReady and afterReady), Play (see onPlay and afterPlay), and Focus (see onFocus and afterFocus). See the EventListener object for a general description of these events.

The method alerts the user and returns null on failure. It does not throw exceptions.

Parameters

args

(optional) A PlayerArgs object.

Returns

A MediaPlayer object, or null on failure

Example 1: This minimal example is a custom JavaScript from the Actions tab in the Multimedia Properties panel of a screen annotation. To override the parameters specified by the UI of the screen annotation, the args parameter is passed.

app.media.openPlayer();

Override settings.repeat : if repeat is set to 1, change it to 2. Otherwise, set it to 1.

var nRepeat =
    ( event.action.rendition.getPlaySettings().repeat == 1 ) ? 2 : 1;
var args = { settings: { repeat: nRepeat } };
app.media.openPlayer(args);

See the event object for an explanation of event.action.rendition. The above example also uses Rendition.getPlaySettings to access the settings associated with the rendition to be played (the one associated with the screen annotation).

Example 2: The following script is executed from a mouse-up action of a form button. It plays a docked media clip in a screen annotation.

app.media.openPlayer({
    rendition: this.media.getRendition( "myClip" ),
    annot: this.media.getAnnot( {nPage:0,cAnnotTitle:"myScreen"} ),
    settings: { windowType: app.media.windowType.docked }
});

Example 3: This example is a custom JavaScript from the Actions tab in the Multimedia Properties of a screen annotation. The user clicks the annotation and a randomly chosen movie clip is played.

   // These are placed at the top level of the document JavaScript
   var myRenditions = new Array();
   myRenditions[0] = "myClip1";
   myRenditions[1] = "myClip2";
   myRenditions[2] = "myClip3";

   // This code is a custom JavaScript of a ScreenAnnot. All renditions

    // are docked and are played in the ScreenAnnot.
   var l = myRenditions.length;
   randomIndex = Math.floor( Math.random() * l ) % l;

   var rendition = this.media.getRendition(myRenditions[randomIndex]);
   var settings = app.media.getRenditionSettings({ rendition: rendition });

   var args = { rendition: rendition, settings: settings }
app.media.openPlayer(args);

removeStockEvents

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Removes any stock EventListeners from a MediaPlayer object and from any associated ScreenAnnot object and deletes the player.stockEvents, player.annot, annot.stockEvents, and annot.player properties. This undoes the effect of a previous addStockEvents call.

Parameters

player

A MediaPlayer object

startPlayer

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Checks whether an annotation is provided in the PlayerArgs object and the annotation already has a player open. If so, it calls player.play on that player to start or resume playback. If not, it calls app.media.openPlayer to create and open a new MediaPlayer object. See openPlayer for more details.

Note

app.media.startPlayer is the default mouse-up action when you use the Acrobat user interface to create a multimedia annotation and rendition and you do not specify any custom JavaScript.

Parameters

args

(optional) A PlayerArgs object

Returns

A MediaPlayer object or null on failure

Example: Start a screen annotation from a form button.

var args = {
    rendition: this.media.getRendition( "myClip" ),
    annot: this.media.getAnnot({ nPage: 0, cAnnotTitle: "myScreen" }),
};
app.media.startPlayer(args);

Bookmark

A Bookmark object represents a node in the bookmark tree that appears in the bookmarks navigational panel. Bookmarks are typically used as a table of contents allowing the user to navigate quickly to topics of interest.

Bookmark properties

children

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

No

No

All

Array null

R

An array of Bookmark objects that are the children of this bookmark in the bookmark tree. If there are no children of this bookmark, this property has a value of null.

See also the parent and bookmarkRoot properties.

Example: Dump all bookmarks in the document.

function DumpBookmark(bkm, nLevel)
{
    var s = "";
    for (var i = 0; i < nLevel; i++) s += " ";
    console.println(s + "+-" + bkm.name);
    if (bkm.children != null)
        for (var i = 0; i < bkm.children.length; i++)
            DumpBookmark(bkm.children[i], nLevel + 1);
}
console.clear(); console.show();
console.println("Dumping all bookmarks in the document.");
DumpBookmark(this.bookmarkRoot, 0);

color

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

Not available in Reader

Array

R/W (Adobe Reader: R only)

Specifies the color for a bookmark. Values are defined by using gray, RGB or CMYK color. See Color arrays for information on defining color arrays and how values are used with this property. See also the style property.

Example: The following fun script colors the top-level bookmark red, green, and blue.

var bkm = this.bookmarkRoot.children[0];
bkm.color = color.black;
var C = new Array(1, 0, 0);
var run = app.setInterval(
    'bkm.color = ["RGB",C[0],C[1],C[2]]; C.push(C.shift());', 1000);
var stoprun=app.setTimeOut(
    "app.clearInterval(run); bkm.color=color.black",12000);

doc

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

No

No

All

Object

R

The Doc that the bookmark resides in.

name

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

Not available in Reader

String

R/W (Adobe Reader: R only)

The text string for the bookmark that the user sees in the navigational panel.

Example: Put the top-level bookmark in bold.

var bkm = this.bookmarkRoot.children[0];
console.println( "Top-level bookmark name: " + bkm.name );

The example that follows the children property also uses the name property.

open

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

Not available in Reader

Boolean

R/W (Adobe Reader: R only)

Determines whether the bookmark shows its children in the navigation panel (open) or whether the children subtree is collapsed (closed).

parent

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

No

No

All

Object null

R

The parent bookmark of the bookmark or null if the bookmark is the root bookmark. See also the children and bookmarkRoot properties.

style

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

D

No

Not available in Reader

Integer

R/W (Adobe Reader: R only)

Specifies the style for the bookmark’s font: 0 is normal, 1 is italic, 2 is bold, and 3 is bold-italic. See also the color property.

Example: The following code puts the top-level bookmark in bold.

var bkm = this.bookmarkRoot.children[0];
bkm.style = 2;

Bookmark methods

createChild

Version (Key)

Save-Prefs

Security

Product

5.0

D

No

Not available in Reader

Creates a new child bookmark at the specified location.

See also the children property and the insertChild and remove methods.

Parameters

Parameter

Description

cName

The name of the bookmark that the user sees in the navigation panel.

cExpr

(optional) An expression to be evaluated whenever the user clicks the bookmark. It is equivalent to creating a bookmark with a JavaScript action, as described in the PDF Reference. The default is no expression.

nIndex

(optional) The 0-based index into the children array of the bookmark at which to create the new child. The default is 0.

Example: Create a bookmark at the top of the bookmark panel that takes you to the next page in the document.

this.bookmarkRoot.createChild("Next Page", "this.pageNum++");

execute

Version (Key)

Save-Prefs

Security

Product

5.0

No

No

All

Executes the action associated with this bookmark. This can have a variety of behaviors. See the PDF Reference for a list of common action types. See also the createChild method.

Example: Implement a simple search of the bookmarks. If successful, the action associated with the bookmark is executed.

// Document-level or folder-level JavaScript.
function searchBookmarks(bkm, nLevel, bkmName)
{
    if ( bkm.name == bkmName ) return bkm;
    if (bkm.children != null) {
        for (var i = 0; i < bkm.children.length; i++)
        {
            var bkMark = searchBookmarks(
                bkm.children[i], nLevel + 1, bkmName);
            if ( bkMark != null ) break;
        }
        return bkMark;
    }
    return null;
}
// Redefine this function for a more sophisticated compare.
function bmkCompare( name1, name2 )
{
        return ( name1 == name2 );
}

The following code initiates the search. This code could be executed as field-level JavaScript or be executed as a menu action.

var bkmName = app.response({
    cQuestion: "Enter the name of the bookmark to find",
    cTitle: "Bookmark Search and Execute"
});
if ( bkmName != null ) {
    var bkm = searchBookmarks(this.bookmarkRoot, 0, bkmName );
    if ( bkm != null ) bkm.execute();
    else app.alert("Bookmark not found");
}

insertChild

Version (Key)

Save-Prefs

Security

Product

5.0

D

No

Not available in Reader

Inserts the specified bookmark as a child of this bookmark. If the bookmark already exists in the bookmark tree, it is unlinked before inserting it back into the tree. In addition, the insertion is checked for circularities and disallowed if one exists. This prevents users from inserting a bookmark as a child or grandchild of itself. See also the children property and the createChild and remove methods.

Parameters

Parameter

Description

oBookmark

A bookmark object to add as the child of this bookmark.

nIndex

(optional) The 0-based index into the children array of the bookmark at which to insert the new child. The default is 0.

Example: Take the first child bookmark and move it to the end of the bookmarks.

var bm = bookmarkRoot.children[0];
bookmarkRoot.insertChild(bm, bookmarkRoot.children.length);

remove

Version (Key)

Save-Prefs

Security

Product

5.0

D

No

Not available in Reader

Removes the bookmark and all its children from the bookmark tree. See also the children property and the createChild and insertChild methods.

Example: Remove all bookmarks from the document.

bookmarkRoot.remove();

setAction

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All but Reader

Sets a JavaScript action for a bookmark.

See also the Doc addRequirement and setPageAction methods and the Field object setAction method.

Note

This method overwrites any action already defined for this bookmark.

Parameters

Parameter

Description

cScript

Defines the JavaScript expression that is to be executed whenever the user clicks the bookmark.

Example: Attach an action to the topmost bookmark.

var bm = bookmarkRoot.children[0]
bm.setAction("app.beep(0);");

catalog

A static object that accesses the functionality provided by the Acrobat Catalog plug-in. This plug-in must be installed to interface with the catalog object.

Note

The Catalog plug-in (and the catalog object) is available only in Acrobat Pro.

See also the index object, which is used to invoke various indexing operations provided by the Catalog plug-in, and the CatalogJob object.

catalog properties

isIdle

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

Acrobat Pro only

Boolean

R

Returns true when Catalog is not busy with an indexing job.

jobs

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

Acrobat Pro only

Array

R

Gets information about the Catalog jobs. Catalog maintains a list of its pending, in-progress, and completed jobs for each Acrobat session. Returns an array of CatalogJob objects.

catalog methods

getIndex

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

Acrobat Pro only

Uses a specified path of a Catalog index to get an Index object. The returned object can be used to perform various indexing operations such as building or deleting an index.

Parameters

cDIPath

The device-independent path of a Catalog index.

Returns

The Index object.

remove

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

Acrobat Pro only

Removes the specified CatalogJob object from Catalog’s job list. Catalog maintains a list of pending, in-progress, and completed jobs for each Acrobat session.

Parameters

Parameter

Description

oJob

The CatalogJob object to remove, as returned by the jobs property and various methods of the Index object.

Example: Delete all jobs that are pending and need complete rebuild.

if (typeof catalog != undefined)  {
    for (var i=0; i<catalog.jobs.length; i++){
        var job = catalog.jobs[i];
        console.println("Index: ", job.path);

        if (job.status == "Pending" && job.type == "Rebuild")
            catalog.remove(job);
    }
}

CatalogJob

This generic JavaScript object provides information about a job submitted to Catalog. It is returned by the build method of the Index object and the catalog.jobs property, and passed to catalog.remove.

CatalogJob properties

path

Device-independent path of the index associated with the job

Type

Access

String

R

type

Type of indexing operation associated with the job.

Type

Access

String

R

Possible values are:

Build
Rebuild
Delete

status

The status of the indexing operation.

Type

Access

String

R

Possible values are:

Pending
Processing
Completed
CompletedWithErrors

Certificate

The Certificate object provides read-only access to the properties of an X.509 public key certificate.

Related objects and methods are:

Field object: signatureInfo * FDF object: signatureValidate * RDN object

  • Usage Object

Note

There are no security restrictions on this object.

Certificate properties

binary

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

No

No

All

String

R

The raw bytes of the certificate, as a hex encoded string.

issuerDN

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

No

No

All

RDN object

R

The distinguished name of the issuer of the certificate, returned as an RDN object.

keyUsage

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

Array of Strings

R

An array of strings indicating the value of the certificate key usage extension. Possible values are

kDigitalSignature    kDataEncipherment    kCRLSign
kNonRepudiation      kKeyAgreement        kEncipherOnly
kKeyEncipherment     kKeyCertSign         kDecipherOnly

MD5Hash

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

No

No

All

String

R

The MD5 digest of the certificate, represented as a hex-encoded string. This provides a unique fingerprint for this certificate.

privateKeyValidityEnd

Version (Key)

Save-Prefs

Security

Product

Type

Access

8.0

No

No

All

Date object

R

The date before which it’s legal to use the private key associated with this certificate. If the PKUP extension is not present or this property isn’t present in the extension, this represents the validity end date of the certificate itself. Before a digital ID can be used for signing, Acrobat ensures that the signing time is prior to the privateKeyValidityEnd date.

privateKeyValidityStart

Version (Key)

Save-Prefs

Security

Product

Type

Access

8.0

No

No

All

Date object

R

The date after which it’s legal to use the private key associated with this certificate. If the Private Key Usage Period (PKUP) certificate extension is not present, this represents the validity start date of the certificate itself. Before a digital ID can be used for signing, Acrobat ensures that the signing time is more recent than the privateKeyValidityStart date.

SHA1Hash

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

No

No

All

String

R

The SHA1 digest of the certificate, represented as a hex-encoded string. This provides a unique fingerprint for this certificate.

serialNumber

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

No

No

All

String

R

A unique identifier for this certificate, used in conjunction with issuerDN.

subjectCN

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

No

No

All

String

R

The common name of the signer.

subjectDN

Version (Key)

Save-Prefs

Security

Product

Type

Access

5.0

No

No

All

RDN object

R

The distinguished name of the signer, returned as an RDN object.

ubRights

Version (Key)

Save-Prefs

Security

Product

Type

Access

7.0

No

No

All

Rights object

R

The application rights that can be enabled by this certificate, returned as a generic Rights object.

Rights Object

A Rights object has the following properties.

Property

Type

Access

Description

mode

String

R

Possible values are:

  • Evaluation: Rights enabled by this certificate for this document are valid as long as this certificate is valid.

  • Production: Rights enabled by this certificate for this document are valid for eternity.

Currently, this value is not used by Adobe’s PDF viewer.

rights

Array of Strings

R

Array of strings indicating the application rights that can be enabled by this certificate. Possible values are:

  • FormFillInAndSave: The right to fill in forms, excluding signature fields, and to save the modified file.

  • FormImportExport: The right to import and export form data.

  • FormAddDelete: The right to add or delete a form field.

  • SubmitStandalone: The right to submit a document outside a browser.

  • SpawnTemplate: The right to spawn page templates.

  • Signing: The right to sign existing form fields in a document.

  • AnnotModify: The right to create, delete, and modify comments.

  • AnnotImportExport: The right to import and export annotations.

  • BarcodePlaintext: The right to encode the appearance of a form field as a plain text barcode.

  • AnnotOnline: Allow online commenting. Enables uploading of any annotations in the document to a server and downloading of annotations from a server. Does not enable the addition of these annotations into the document.

  • FormOnline: Enable forms-specific online mechanisms such as SOAP or Active Data Object.

  • EFModify: The right to create, delete, modify, and import named embedded files. Does not apply to file attachment annotations.

usage

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

All

Usage object

R

The purposes for which this certificate may be used within the Acrobat environment returned as a Usage object.

Usage Object

This generic JavaScript object represents a certificate usage value in the certificate.usage property. It has the following properties.

Property

Type

Access

Description

endUserSigning

Boolean

R

true if the certificate is usable for end-user signing.

endUserEncryption

Boolean

R

true if the certificate is usable for end-user encryption.

Example: Encrypt the currently open document for everyone in the address book. Address book entries that contain sign-only certificates, CA certificates, no certificates, or are otherwise unsuitable for encryption, are not included in the final recipient list.

var eng = security.getHandler( "Adobe.AAB" );
var dc = eng.directories[0].connect();
var recipients = dc.search();

var filteredRecipients = new Array();
for( i = 0; i < recipients.length; ++i ) {
    if( recipients[i].defaultEncryptCert &&
        recipients[i].defaultEncryptCert.usage.endUserEncryption ) {
        filteredRecipients[filteredRecipients.length] = recipients[i];
        continue;
    }
    if(recipients[i].certificates) {
        for( j = 0; j < recipients[i].certificates.length; ++j )
            if( recipients[i].certificates[j].usage.endUserEncryption ) {
                filteredRecipients[filteredRecipients.length]

                     = recipients[i];
                continue;
            }
    }
}
this.encryptForRecipients({
    oGroups:[{userEntities: filteredRecipients}]
});

validityEnd

Version (Key)

Save-Prefs

Security

Product

Type

Access

7.05

No

No

All

Date object

R

The validity end date of the certificate. Before a digital ID can be used for signing, Acrobat ensures that the signing time is prior to the validityEnd date.

validityStart

Version (Key)

Save-Prefs

Security

Product

Type

Access

7.05

No

No

All

Date object

R

The validity start date of the certificate. Before a digital ID can be used for signing Acrobat, ensures that the signing time is more recent than the validityStart date.

Collab

This static object represents the collaboration functionality.

Collab methods

addStateModel

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Adds a new state model to Acrobat. A state model describes the valid states that an annotation using the model can have (see the Annotation object for details about getting and setting the state of an annotation). State models can be used to describe the workflow that a document review goes through and can be used for review management.

See also removeStateModel, getStateInModel, and transitionToState.

Parameters

Parameter

Description

cName

A unique, language-independent identifier for the State Model.

cUIName

The display name of the state model used in the user interface. The value should be a localized string.

oStates

The states in the state model, described by a States object.

cDefault

(optional) One of the states in the model to be used as a default state if no other state is set. The default is for there to be no default state.

bHidden

(optional) Specifies whether the state model should be hidden in the state model user interface. The default is false (the State Model is shown).

bHistory

(optional) Specifies whether an audit history is maintained for the state model. Keeping an audit history requires more space in the file. The default is true.

States object

This generic object represents a set of states in a state model and is passed as the oStates parameter. The elements in the object literal are the unique state identifiers and the values are objects having the following properties:

Property

Description

cUIName

The UI (display name) for the state.

oIcon

(optional) An Icon Stream object that is displayed in the UI for the state.

Example: Add a new state model with a unique name of “ReviewStates”:

Collab.addStateModel({
    cName: "ReviewStates",
    cUIName: "My Review",

     oStates:
    {
        "initial": {cUIName: "Haven't reviewed it"},
        "approved": {cUIName: "I approve"},
        "rejected": {cUIName: "Forget it"},
        "resubmit": {cUIName: "Make some changes"}
    },
    cDefault: "initial"
});

A state model can be removed with Collab.removeStateModel.

documentToStream

Version (Key)

Save-Prefs

Security

Product

7.0.5

No

Yes

All

Saves a copy of a Doc and returns the contents as a stream object.

The document dirty property is preserved after this method is called and the original document is not modified.

Parameters

oDocument

The Doc.

Returns

A ReadStream object.

removeStateModel

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

All

Removes a state model that was previously added by calling addStateModel. Removing a state model does not remove the state information associated with individual annotations. If the model is removed and added again, all of the state information for the annotations is still available.

See also addStateModel, getStateInModel, and transitionToState.

Parameters

Parameter

Description

cName

A unique, language-independent identifier for the state model that was used in addStateModel.

Example: Continuing the example in addStateModel, remove the state model “ReviewStates”:

// Remove the state model
Collab.removeStateModel("ReviewStates");

color

The color object is a convenience static object that defines the basic colors. Use this object to set a property or call a method that requires a color array.

Color arrays

A color is represented in JavaScript as an array containing 1, 2, 4, or 5 elements corresponding to a Transparent, Gray, RGB, or CMYK color space, respectively. The first element in the array is a string denoting the color space type. The subsequent elements are numbers that range between zero and one inclusive. For example, the color red can be represented as ["RGB", 1, 0, 0].

Invalid strings or insufficient elements in a color array cause the color to be interpreted as the color black.

Color space

String

Number of additional elements

Description

Transparent

“T”

0

A transparent color space indicates a complete absence of color and allows those portions of the document underlying the current field to show through.

Gray

“G”

1

Colors are represented by a single value—the intensity of achromatic light. In this color space, 0 is black, 1 is white, and intermediate values represent shades of gray. For example, .5 represents medium gray.

RGB

“RGB”

3

Colors are represented by three values: the intensity of the red, green, and blue components in the output. RGB is commonly used for video displays, which are generally based on red, green, and blue phosphors.

CMYK

“CMYK”

4

Colors are represented by four values, the amounts of the cyan, magenta, yellow, and black components in the output. This color space is commonly used for color printers, where they are the colors of the inks used in four-color printing. Only cyan, magenta, and yellow are necessary, but black is generally used in printing because black ink produces a better black than a mixture of cyan, magenta, and yellow inks and because black ink is less expensive than the other inks.

color properties

The color object defines the following colors.

Color object

Keyword

Equivalent JavaScript

Version

Transparent

color.transparent

[ "T" ]

Black

color.black

[ "G", 0 ]

White

color.white

[ "G", 1 ]

Red

color.red

[ "RGB", 1,0,0 ]

Green

color.green

[ "RGB", 0,1,0 ]

Blue

color.blue

[ "RGB", 0, 0, 1 ]

Cyan

color.cyan

[ "CMYK", 1,0,0,0 ]

Magenta

color.magenta

[ "CMYK", 0,1 0,0 ]

Yellow

color.yellow

[ "CMYK", 0,0,1,0 ]

Dark Gray

color.dkGray

[ "G", 0.25 ]

4.0

Gray

color.gray

[ "G", 0.5 ]

4.0

Light Gray

color.ltGray

[ "G", 0.75 ]

4.0

Example: This example sets the text color of the field to red if the value of the field is negative, or to black if the field value is nonnegative.

var f = event.target; /* field that the event occurs at */
f.target.textColor = event.value < 0 ? color.red : color.black;

color methods

convert

Version (Key)

Save-Prefs

Security

Product

5.0

No

No

All

Converts the color space and color values specified by the color object to the specified color space:

  • Conversion to the gray color space is lossy (in the same fashion that displaying a color TV signal on a black-and-white TV is lossy).

  • The conversion of RGB to CMYK does not take into account any black generation or undercolor removal parameters.

Parameters

Parameter

Description

colorArray

Array of color values. See Color arrays.

cColorspace

The color space to which to convert.

Returns

A color array.

Example: The return value of the code line below is the array ["CMYK", 0, 1, 1, 0].

color.convert(["RGB",1,0,0], "CMYK");

equal

Version (Key)

Save-Prefs

Security

Product

5.0

No

No

All

Compares two Color Arrays to see if they are the same. The routine performs conversions, if necessary, to determine if the two colors are indeed equal (for example, ["RGB",1,1,0] is equal to ["CMYK",0,0,1,0]).

Parameters

colorArray1

The first color array for comparison.

colorArray2

The second color array for comparison.

Returns

true if the arrays represent the same color, false otherwise.

Example:

var f = this.getField("foo");
if (color.equal(f.textColor, f.fillColor))
    app.alert("Foreground and background color are the same!");

colorConvertAction

This object describes a single color conversion action.

You can obtain colorConvertAction object from the Doc object method getColorConvertAction. The returned object can then be modified. A color conversion action is divided into a “match” section and an “action” section. The “match” section describes what sorts of objects can match this action. The Doc object method colorConvertPage, accepts an array of these actions, against which matches are attempted until a match is found.

colorConvertAction properties

action

Version (Key)

Save-Prefs

Security

Product

Type

Access

8.0

No

No

Acrobat Pro only

Integer

R/W

Describes the action to perform if a match occurs.

The value of action is accessed through the constants.actions object of the colorConvertAction object as the following constants:

constants.actions object

Name

Description

Preserve

Do nothing but handle ink aliases.

Convert

Convert to target space.

Decalibrate

Convert calibrated space to device.

DownConvert

Downconvert NChannel to DeviceN.

alias

Version (Key)

Save-Prefs

Security

Product

Type

Access

8.0

No

No

Acrobat Pro only

String

R/W

If this action is an ink action then this describes the ink’s alias.

colorantName

Version (Key)

Save-Prefs

Security

Product

Type

Access

8.0

No

No

Acrobat Pro only

String

R/W

If this action is an ink action then this describes the colorant name.

See the related property isProcessColor.

convertIntent

Version (Key)

Save-Prefs

Security

Product

Type

Access

8.0

No

No

Acrobat Pro only

Integer

R/W

Defines the rendering intent used to color convert the object. For a detailed description of rendering intents, please see Table 4.20 of the PDF Reference.

The value of convertIntent is accessed through the constants.renderingIntents object of the colorConvertAction object.

convertProfile

Version (Key)

Save-Prefs

Security

Product

Type

Access

8.0

No

No

Acrobat Pro only

String

R/W

Describes the color profile to which matching objects should be converted if the action is Convert. A list of available color profiles can be obtained from the printColorProfiles property of the app object

embed

Version (Key)

Save-Prefs

Security

Product

Type

Access

8.0

No

No

Acrobat Pro only

Boolean

R/W

If the matched object is to be converted and embed is true, the resulting object will have a color profile embedded in the file. Otherwise, the object will be stored as the corresponding device color space for the profile to which the object was converted.

isProcessColor

Version (Key)

Save-Prefs

Security

Product

Type

Access

8.0

No

No

Acrobat Pro only

Boolean

R/W

If this action is an ink action and if isProcessColor is true, the ink represents a process color, and the colorantName should be one of Cyan, Magenta, Yellow, Black, Red, Green or Blue.

matchAttributesAll

Version (Key)

Save-Prefs

Security

Product

Type

Access

8.0

No

No

Acrobat Pro only

Integer

R/W

The value of the matchAttributesAll property is a bitmap containing object attributes (flags) to be matched. A match occurs if all flags match, i.e. if there is a complete match.

The flags are accessed through the constants.objectFlags object of the colorConvertAction object and are defined as follows:

constants.objectFlags object

Flag name

Description

ObjImage

Object is an image.

ObjJPEG

Object is a JPEG image.

ObjJPEG2000

Object is a JPEG2000 Image.

ObjLossy

Image in a lossy space.

ObjNonLossy

Image in a non-lossy space.

ObjText

Object is text.

ObjLineArt

Object is line-art (fill or stroke).

ObjShade

Object is a smooth shade.

ObjTransparent

Object is not opaque.

ObjOverprinting

Object overprints.

ObjOverprintMode

OPM is set to 1.

Note

The value of matchAttributesAll can be set by using the bitwise operators with the bit flags of constants.objectFlags.

Example: Match images that overprint.

var action = this.getColorConvertAction();
action.matchAttributesAll = action.constants.objFlags.ObjImage
               action.constants.objFlags.ObjOverprinting;

matchAttributesAny

Version (Key)

Save-Prefs

Security

Product

Type

Access

8.0

No

No

Acrobat Pro only

Integer

R/W

The value of the matchAttributesAny property is a bitmap containing object attributes to be matched. A match occurs if any of the flags match.

The flags are accessed through the constants.objectFlags object of the colorConvertAction object.

Note

The value of matchAttributesAny can be set by using the bitwise operators with the bit flags of constants.objectFlags.

matchIntent

Version (Key)

Save-Prefs

Security

Product

Type

Access

8.0

No

No

Acrobat Pro only

Integer

R/W

Matches the rendering intent used for the object. For a detailed description of rendering intents, please see Table 4.20 of the PDF Reference.

The value of matchIntent is accessed through the constants.renderingIntents object of the colorConvertAction object and are defined as follows:

constants.renderingIntents object

Name

Description

AbsoluteColorimetric

Absolute colorimetric rendering intent.

RelativeColorimetric

Relative colorimetric rendering intent.

Saturation

Saturation rendering intent

Perceptual

Perceptual rendering intent

Any

Match any of the above rendering intents

Document

Use the rendering intent specified by the current graphics state in which the matched object is rendered (used by convertIntent only).

matchSpaceTypeAll

Version (Key)

Save-Prefs

Security

Product

Type

Access

8.0

No

No

Acrobat Pro only

Integer

R/W

The value of the matchSpaceTypeAll property is a bitmap containing color space attributes (flags) to be matched. A match occurs if all flags match, i.e. if there is a complete match.

These two fields are bitmaps containing color space attributes to be matched. The first field will only match if all flags match, i.e. if there is a complete match. The second field will match if any of the flags match.

The flags are accessed through the constants.spaceFlags object of the colorConvertAction object and are defined as follows:

constants.spaceFlags object

Flag name

Description

DeviceSpace

Color space is one of DeviceRGB, DeviceCMYK, or DeviceGray.

CalibratedSpace

Color space is ICCBased, CalRGB, CalGray, or Lab.

AlternateSpace

This color space is the alternate space of a DeviceN, Separation, or ICCBased.

BaseSpace

This color space is the base space of an Indexed space.

IndexedSpace

This color space is an indexed space.

SeparationSpace

This color space is a Separation color space.

DeviceNSpace

This color space is a DeviceN color space.

NChannelSpace

This color space is a DeviceN color space with NChannel attributes.

RGBSpace

This space is RGB. This flag should only be used in combination with DeviceSpace or CalibratedSpace.

CMYKSpace

This space is CMYK. This flag should only be used in combination with DeviceSpace or CalibratedSpace.

GraySpace

This space is Grayscale. This flag should only be used in combination with DeviceSpace or CalibratedSpace.

LabSpace

This space is CIELAB. This flag should only be used in combination with DeviceSpace or CalibratedSpace.

Note

The value of matchSpaceTypeAll can be set by using the bitwise operators with the bit flags of constants.spaceFlags.

matchSpaceTypeAny

Version (Key)

Save-Prefs

Security

Product

Type

Access

8.0

No

No

Acrobat Pro only

Integer

R/W

The value of the matchSpaceTypeAny property is a bitmap containing color space attributes (flags) to be matched. A match occurs if any of the flags match.

The flags are accessed through the constants.spaceFlags object of the colorConvertAction object.

Note

The value of matchSpaceTypeAny can be set by using the bitwise operators with the bit flags of constants.spaceFlags.

preserveBlack

Version (Key)

Save-Prefs

Security

Product

Type

Access

8.0

No

No

Acrobat Pro only

Boolean

R/W

If the matched object is to be converted and preserveBlack is true, the conversion will be done using a “black-preserving” transform, in which text or line art objects are handled specially. If a CMYK color is (0.0, 0.0, 0.0, 1.0), an RGB color is (0.0, 0.0, 0.0) or a gray color is (0.0), and preserveBlack is true, that color is considered special-case black, and is converted straight to black without using the conversion profile. The resulting color will be as described for the matching black color for the corresponding profile target color space, for example, if the convert profile is RGB, the resulting color will be (0.0, 0.0, 0.0) no matter what the color profile says.

useBlackPointCompensation

Version (Key)

Save-Prefs

Security

Product

Type

Access

8.0

No

No

Acrobat Pro only

Boolean

R/W

If useBlackPointCompensation is true, use black point compensation for all color conversions. The effect of this flag depends on the color management method (CMM) being used, but if the Adobe CMM is being used, colorimetric transforms are scaled such that black remains black no matter what the media black point of the source profile.

Collection

A collection object is obtained from the Doc. collection property. Doc. collection returns a null value when there is no PDF collection (also called PDF package and PDF portfolio).

The collection object is used to set the initial document in the collection, set the initial view of the collection, and to get, add, and remove collection fields (or categories).

Collection properties

fields

Version (Key)

Save-Prefs

Security

Product

Type

Access

8.0

No

No

All

Array

R/W

The fields property is an array of collectionField objects in the collection.

Example: Enumerate all the collectionFields in a collection.

for (var i in collection.fields)

console.println(i);

initialDoc

Version (Key)

Save-Prefs

Security

Product

Type

Access

9.0

No

No

All

String

R/W

Use the initialDoc property to specify the document in the collection that is initially viewed when the collection is opened. The value of initialDoc is the name property of the data object of the initial document, or null if no initial document is specified.

Example: Set the initial document to the third file in the collection.

this.collection.initialDoc = this.dataObjects[2].name;

initialView

Version (Key)

Save-Prefs

Security

Product

Type

Access

9.0

No

No

All

String

R/W

A string describing the initial collection view. Possible values include Tile, Details, Hidden, Custom, or null. The values of Tile and Details are built-in views, while Custom indicates that a document-based Navigator is preferred.

Example: Set the initial view to Details.

this.collection.initialView = "Details";

Collection methods

addField

Version (Key)

Save-Prefs

Security

Product

9.0

No

No

All

Adds a new field (or category) to the collection schema. The method throws an exception if the field already exits.

name

A string that is the name of the field of the collectionField object to be added.

text

The text of this field that is displayed to the user in the user interface.

type

(Optional) A string that specifices the type of data associated with the field. Possible values are are listed below. S, a string type. A field with a string value. D, a date type. A field with a date value. N, a numeric type. A field with a numeric value. The following values identify the types of file-related fields: F, a field reserved for the file name of a member of the collection. Desc, a field reserved for a description string of a member of the collection. Size, a ield reserved for the file size of a member of the collection. ModDate, a field reserved for the modification date of a member of the collection. CreationDate, a field reserved for the creation date of a member of the collection. CompressedSize, a field reserved for the compressed file size of a member of the collection. The default is "S", a string type.

order

(Optional) An integer that indicates the order of the field in the display of the collection in the user interface. If this parameter is not specified, the new field is listed last.

visible

(Optional) A Boolean value that indicates the visibility of the field. The field is visible if the the value is true ; not visible if false. The default is true.

readOnly

(Optional) A Boolean value, the field is read only if true. The default is false. If a field is read only, the user is not allowed to change the value of this field through the user interface.

Returns

The collectionField object of the newly created field.

Example: Create a new field in the collection called "to" using object literal techniques.

this.collection.addField({name:"to", order:3, text:"To", type:"S"});

// The same example as above, but using ordered parameters.
this.collection.addField("to", "To", "S", 3);

getField

Version (Key)

Save-Prefs

Security

Product

9.0

No

No

All

The getField method returns the collectionField object corresponding to the name of a collection field.

Parameters

Parameter

Description

name

A string that is the name of the field of the collectionField object to be retrieved.

Returns

A collectionField object, or null if the field is not found.

Example: Get the collectionField object of the "from" field.

var f = this.collection.getField("from");

removeField

Version (Key)

Save-Prefs

Security

Product

9.0

No

No

All

Remove a field from the collection schema.

Parameters

name

A string that is the name of the field to be removed.

Example: Remove the "from" field from the collection schema.

this.collection.removeField("from");

collectionField

The properties of the collectionField object are the fields (or categories) used by the collection. The text property (see below) is the (display) string the user sees in the user-interface with viewing a listing of the files files in the collection. Use the collectionField object to set the order the fields are listed in the user-interface, the sort order of the listing of the files, or to set a field as read only.

The collection field values for embedded files in the collection can be got or set through getFieldValue and setFieldValue methods of the data object.

collectionField properties

name

Version (Key)

Save-Prefs

Security

Product

Type

Access

9.0

No

No

All

String

R

The string that specifies the name of the field.

order

Version (Key)

Save-Prefs

Security

Product

Type

Access

9.0

No

No

All

Integer

R/W

Specifies the order the field is listed in relation to other fields. Field order is 0-based. When changing the value, if needed, the order of other fields will be incremented to prevent duplicates.

readOnly

Version (Key)

Save-Prefs

Security

Product

Type

Access

9.0

No

No

All

Boolean

R/W

A Boolean value that specifies whether the user may change values of the field in the user interface. When readonly is true, no changes are allowed.

sort

Version (Key)

Save-Prefs

Security

Product

Type

Access

9.0

No

No

All

Integer

R/W

The value of sort specifies how this field contributes to the ordering of files in the collection.

If the value is 0, this field is not used to sort the files. If the absolute value is 1, this field is the primary sort field. If the absolute value is 2, the field is the secondary sort field (used to break ties on the primary sort field), and so on. Additionally, the sign of value indicates the direction in which the files should be sorted. Positive values indicate that the files are sorted in ascending order, and negative values indicate that files are sorted in descending order.

Example: To illustrate the sorting scheme, consider a simple set of 4 fields that describe an email inbox: From, Subject, To, and Received. Each file in the collection represents a single email message. Set the sort order for each of these fields as indicated below:

  • From: 0

  • To: 0

  • Subject: 1

  • Received: -2

The above sort order indicates that the primary sort field is "Subject" (the absolute value of the field is 1) and that files should be sorted in ascending order (the sign is positive). If two files have the same subject, the secondary sort field is consulted. In this case, the secondary sort field is "Received" (the absolute value of the field is 2) and it is specified to sort in descending order. The files are sorted by Subject in ascending order. Any files that have identical Subjects will be sorted in a subgroup by their Received field, but in descending order. The other fields do not contribute to the sort, since they are 0.

text

Version (Key)

Save-Prefs

Security

Product

Type

Access

9.0

No

No

All

String

R/W

The value of text specifies the display text used by the field in the user-interface.

type

Version (Key)

Save-Prefs

Security

Product

Type

Access

9.0

No

No

All

String

R/W

A text string that specifies the type of data stored in the field. Possible values include:

  • S, the value of this field is a string type.

  • D, the value of this field is a date type.

  • N, the value of this field is a number type.

  • F, the value of this field is the file name of a member of the collection.

  • Desc, the value of this field is a description string of a member of the collection.

  • Size, the value of this field is the file size of a member of the collection.

  • ModDate, the value of this field is the modification date of a member of the collection.

  • CreationDate, the value of this field is the creation date of a member of the collection.

  • CompressedSize, the value of this field is the compressed file size of a member of the collection.

The value of this property cannot be changed for a field that already exists. When a new field is created using the addField method, the type can be set.

Example: Modify and examine the properties of user-defined field "from".

var f = this.collection.getField("from");
f.visible = true;
f.order = 1;
f.text = "From";
console.println("Field name: " + f.name);
console.println("Field type: " + f.type);

Column

This generic JavaScript object contains the data from every row in a column. A column object is returned by the getColumn and getColumnArray methods of the Statement object. See also the ColumnInfo object.

Column properties

columnNum

START HERE

The number identifying the column.

Type

Access

Number

R

name

The name of the column.

Type

Access

String

R

type

One of the SQL Types for the data in the column.

Type

Access

Number

R

typeName

The name of the type of data the column contains.

Type

Access

String

R

value

The value of the data in the column, in the format in which the data was originally retrieved.

Type

Access

various

R/W

ColumnInfo

This generic JavaScript object contains basic information about a column of data. It is returned by the getColumnList method of the Connection object. See also the Column object.

ColumnInfo properties

name

A string that represents the identifying name of a column. This string can be used in a call to the getColumn method of the Statement object identify the associated column.

Type

Access

String

R

description

A string that contains database-dependent information about the column.

Type

Access

String

R

type

A numeric value identifying one of the ADBC SQL Types that applies to the data contained in the column associated with the ColumnInfo object.

Type

Access

Number

R

typeName

Type

Access

String

R

A string identifying the type of the data contained in the associated column. It is not one of the SQL Types (see type above), but a database-dependent string representing the data type. This property may give useful information about user-defined data types.

console

The console object is a static object that enables access to the Acrobat JavaScript Console for executing JavaScript and displaying debug messages.

This object does not function in Adobe Reader versions earlier than 7.0. Beginning with version 7.0, Adobe Reader has a console window. Its primary function is to report errors and messages. This capability is controlled by the JavaScript preference Show Console on Errors and Messages. Though the console is not interactive, the methods of the console object function as they do in Acrobat.

The debugging capability of the Acrobat JavaScript Debugging window can be made available for Adobe Reader for the Windows and Mac OS platforms. To debug within Adobe Reader, the JavaScript file debugger.js must be installed and the Windows registry must be edited appropriately. See the JavaScript Developer Guide for technical details.

See also the dbg object.

console methods

clear

Version (Key)

Save-Prefs

Security

Product

3.01

No

No

All

Clears the console windows buffer of any output.

hide

Version (Key)

Save-Prefs

Security

Product

4.0

No

No

All

Closes the console window.

println

Version (Key)

Save-Prefs

Security

Product

3.01

No

No

All

Prints a string value to the console window with an accompanying carriage return.

Parameters

cMessage

A string message to print.

Example 1: This example prints the value of a field to the console window. The script could be executed during a mouse-up event.

var f = this.getField("myText");
console.clear(); console.show();
console.println("Field value = " + f.value);

Example 2: The console can be used as a debugging tool. For example, you can write values of variables to the console. The following script is at the document level:

var debugIsOn = true;
function myFunction ( n, m )
{
    if (debugIsOn)
    {
        console.println("Entering function: myFunction");
        console.println(" Parameter 1: n = " + n);
        console.println(" Parameter 2: m = " + m);
    }
    ....
    ....
    if (debugIsOn) console.println(" Return value: rtn = " + rtn);
    return rtn;
}

Beginning with Acrobat 6.0, debugging can also be accomplished with the JavaScript Debugger. See the dbg object.

show

Version (Key)

Save-Prefs

Security

Product

3.01

No

No

All

Shows the console window.

Example: Clear and show the console window:

console.clear();
console.show();

Data

Version (Key)

Save-Prefs

Security

Product

5.0

No

No

All

The Data object is the representation of an embedded file or data stream that is stored in the document. See the PDF Reference for details.

Using Data objects is a good way to associate and embed source files, metadata, and other associated data with a document. Data objects can be inserted from the external file system, queried, and extracted.

See the following Doc properties and methods:

The following objects, properties and methods support PDF portfolios (also called PDF collections or PDF packages):

Note

The Data object methods were implemented in Acrobat 5.0. However, the ability to use them in Adobe Reader with additional usage rights only became available in Adobe Reader 6.0.

Data properties

creationDate

The creation date of the file that was embedded.

Type

Access

Date

R

description

Version (Key)

Save-Prefs

Security

Product

Type

Access

7.05

No

No

All

String

R/W

The description associated with this data object.

MIMEType

The MIME type associated with this data object.

Type

Access

String

R

modDate

The modification date of the file that was embedded.

Type

Access

Date

R

name

The name associated with this data object.

Type

Access

String

R

Example: Display the names of file attachments to this document.

console.println("Dumping all data objects in the document.");
var d = this.dataObjects;
for (var i = 0; i < d.length; i++)
    console.println("DataObject[" + i + "]=" + d[i].name);

path

The file name and extension of the file that was embedded.

Type

Access

String

R

size

The size, in bytes, of the uncompressed data object.

Type

Access

Number

R

Data methods

getFieldValue

Version (Key)

Save-Prefs

Security

Product

9.0

No

No

All

Get the value of the field as specified by the name parameter for this embedded file. When attempting to get a field value that is not defined in the collection schema, null is returned.

Parameters

Parameter

Description

name

A string that identifies the field of interest.

includePrefix

(Optional) A Boolean value indicating whether the prefix should be included with the returned string. If true, the prefix is included with the return string. The default is false.

Returns

The value of the field, or null if field is not present in schema.

setFieldValue

Version (Key)

Save-Prefs

Security

Product

9.0

No

No

All

Type conversion is performed when setting field values. The type conversion is determined by the collectionField in the schema. When attempting to set a field value that is not defined in the schema, an exception is raised.

Parameters

Parameter

Description

name

A string that identifies the field of interest. An exception raised if name not present in schema.

value

A string, a number, or a date that specifies the value of the field. The value will be type-coerced to match the schema.

prefix

(Optional) A string that specifies the field value prefix.

Returns

The value of the field, or null if field is not present in schema.

Example: Get and set field values of the first data object in this collection.

var d = this.dataObjects[0];
d.setFieldValue("subject", "New laptop!", "RE: ");

// Now get the same field value we just set. Here s = "RE: New laptop!"
var s = d.getFieldValue({ name:"subject", includePrefix:true });

// Get the same field value, with includePrefix set to false, the default
// Now the value of s is "New laptop!".
s = d.getFieldValue("subject");

// Sets subject to "A. C. Robat" and clears prefix
d.setFieldValue("subject", "A. C. Robat");

DataSourceInfo

This generic JavaScript object contains basic information about a database. The ADBC.getDataSourceList method returns an array of these objects.

DataSourceInfo properties

name

A string that represents the identifying name of a database. This string can be passed to newConnection to establish a connection to the database that the DataSourceInfo object is associated with.

Type

Access

String

R

description

A string that contains database-dependent information about the database.

Type

Access

String

R

dbg

The dbg object is a static object that can be used to control the JavaScript Debugger from a command-line console. Its methods provide the same functionality as the buttons in the JavaScript Debugger dialog box toolbar. In addition, breakpoints can be created, deleted, and inspected using the dbg object.

The dbg object and the JavaScript Debugger are only available in Acrobat Pro.

Note

If the viewer locks up during a debugging session, pressing Esc may resolve the problem.

Debugging is not possible with a modal dialog box open; for example, when debugging a batch sequence.

Debugging a script with a running event initiated by either app.setInterval or app.setTimeOut may cause recurring alert boxes to appear. Use Esc after the modal dialog box is dismissed to resolve the problem.

(Acrobat 7.0) While the Debugger is open and a debugging session is under way, the Acrobat application is unavailable.

dbg properties

bps

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

No

P

Array

R

An array of breakpoint generic objects corresponding to breakpoints set in the debugger. This object contains the following properties and methods.

Property

Type

Access

Description

fileName

string

R

A string that identifies the script in the debugger.

condition

string

R

A JavaScript expression evaluated by the debugger to decide to whether to stop at a breakpoint. Used to create conditional breakpoints. The default value for this property is the string “true”.

lineNum

number

R

The line number in the script for which the breakpoint is set.

Method

Parameters

Returns

Description

toString

none

String

A string describing the breakpoint.

Example: List all currently active breakpoints.

var db = dbg.bps
for ( var i = 0; i < db.length; i++ )
{
    for ( var o in db[i] ) console.println(o + ": " + db[i][o]);
    console.println("------------------------------------");
}

See sb for another example of usage.

dbg methods

c

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

Acrobat Pro only

The c (continue) method resumes execution of a program stopped in the debugger. The JavaScript program may either stop again, depending on where the breakpoints are set, or reach execution end.

cb

Version (Key)

Save-Prefs

Security

Product

6.0

D

No

Acrobat Pro only

The cb (clear breakpoint) method clears a breakpoint in the debugger. The dbg.cb method dirties the document only if breakpoints are stored in the document, as set through the user preferences, Edit > Preferences > JavaScript.

Parameters

Parameter

Description

fileName

The name of the script from where the breakpoint is going to be deleted.

lineNum

The line number for the breakpoint that is going to be cleared in the script.

q

Version (Key)

Save-Prefs

Security

Product

6.0

D

No

Acrobat Pro only

The q (quit) method quits debugging and executing the current JavaScript. It additionally dismisses the debugger dialog box.

sb

Version (Key)

Save-Prefs

Security

Product

6.0

D

No

Acrobat Pro only

The sb (set breakpoint) method sets a new breakpoint in the debugger. The dbg.sb method dirties the document only if breakpoints are stored in the document, as set through the user preferences, Edit > Preferences > JavaScript.

Parameters

Parameter

Description

fileName

The name of the script where the breakpoint is to be set.

lineNum

The line number in the script to create the breakpoint.

condition

(optional) a JavaScript expression to be evaluated when the debugger reaches the breakpoint. If the expression evaluates to true, the debugger stops at the breakpoint. If the expression evaluates to false, the debugger continues executing the script and does not stop at the breakpoint. The default value is true.

Example 1: Some script is run and an exception is thrown due to some error. A breakpoint is programmatically set using the information given in the error message.

SyntaxError: missing ; before statement 213:Document-Level: myDLJS
// now set a breakpoint using the console
dbg.sb({
    fileName: "Document-Level: myDLJS",
    lineNum: 213,
    condition: "true"
});

Example 2: Simulate the functionality of the Store Breakpoints in PDF File check box in the JavaScript user preferences.

// Save breakpoints in PDF file
this.addScript("myBreakpoints", "var myBPS = " + dbg.bps.toSource());

// Now reset the breakpoints
for ( var i = 0; i < myBPS.length; i++ ) dbg.sb( myBPS[i] );

Example 3: Set a conditional break. Consider the following code, which is a mouse-up action.

for (var i=0; i<100; i++)
    myFunction(i);          // defined at document level

// In the console, set a conditional break. Here, we break when the

 // index of the loop is greater than 30.
dbg.sb({
    fileName:"AcroForm:Button1:Annot1:MouseUp:Action1",
    lineNum:2,
    condition:"i > 30"
})

si

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

Acrobat Pro only

The si (step in) method advances the program pointer to the next instruction in the JavaScript program, entering each function call for which there is a script defined. (Native JavaScript calls cannot be stepped into.)

sn

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

Acrobat Pro only

The sn (step instruction) method advances the program pointer to the next bytecode in the JavaScript program. (Each JavaScript instruction is made up of several bytecodes as defined by the JavaScript interpreter.)

so

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

Acrobat Pro only

The so (step out) method executes the program until it exits the current function. Execution stops at the instruction immediately following the call to the current function. If the scope currently under debug is the top-level scope, the program either continues executing until it ends or stops again when it reaches a breakpoint.

sv

Version (Key)

Save-Prefs

Security

Product

6.0

No

No

Acrobat Pro only

The sv (step over) method advances the program pointer to the next instruction in the JavaScript program. If a function call is encountered, the debugger does not step into the instructions defined inside that function.

Dialog

An instance of this object is passed as a parameter to dialog box handlers (see Dialog box handlers). These handlers include the initialize, validate, commit, destroy and ItemID methods of the dialog box descriptor object literal that is passed to app.execDialog. The Dialog object allows the current state of the Dialog to be queried and set.

Dialog methods

enable

Version (Key)

Save-Prefs

Security

Product

7.0

No

No

All

Enables or disables various dialog box elements using the object literal passed in.

Typically, enable is called in the initialize method (see Dialog box handlers) of the object literal passed to app.execDialog to preset whether various dialog box elements are enabled or not.

Parameters

Parameter

Description

object literal

For each dialog box item to modify, there should be an entry in the object literal with the Dialog ItemID as the label and a Boolean value as the value indicating if it is enabled or not.

Example: See the examples following app. execDialog.

end

Version (Key)

Save-Prefs

Security

Product

7.0

No

No

All

Terminates a currently executing dialog box (as if the Cancel button had been pressed). This method takes an optional parameter of the ItemID, a string, of the dialog box element that will be reported as dismissing the dialog. This ItemID will be the return value of the app.execDialog call that created the dialog.

Parameters

Parameter

Description

String

(optional) The ItemID of the dialog box element that will be reported as dismissing the dialog.

Example: See the examples following app. execDialog.

load

Version (Key)

Save-Prefs

Security

Product

7.0

No

No

All

Sets the values of dialog box elements using the object literal passed in. Dialog box items are identified by an ItemID which is a unique 4-character string.

Typically, load is called in the initialize method (see Dialog box handlers) of the object literal passed to app.execDialog to preset the value of various dialog box elements.

Parameters

Parameter

Description

object literal

For each dialog box item to be modified, there should be an entry in the object literal with the ItemID as the label and the dialog box element setting as the contents. If the dialog box element takes multiple values (for example, a list_box or a popup), the value should be an object literal consisting of the displayed entry as the label and a numeric value as the contents. Similarly, if the dialog box element is hierarchical in nature (for example, a hier_list_box), the value should be a set of nested object literals. If the numeric value is greater than 0, the item is selected, otherwise it is not selected.

Example: See the examples following app. execDialog.

store

Version (Key)

Save-Prefs

Security

Product

7.0

No

No

All

Gets the values of dialog box elements as an object literal returned. Dialog box items are identified by an ItemID, which is a unique 4-character string. For each dialog box element, there will be an entry in the object literal with the ItemID as the label and the dialog box element setting as the contents. If the dialog box element takes multiple values (for example, a list_box or a popup), the value should be an object literal consisting of the displayed entry as the label and a numeric value as the contents. If the numeric value is greater than 0, the item was selected, otherwise it was not selected.

Typically, store is called in the commit method (see Dialog box handlers) of the object literal passed to app.execDialog to extract the value of various dialog box elements.

Returns

object literal

DirConnection

Version (Key)

Save-Prefs

Security

Product

6.0

No

Yes

All

This object represents an open connection to a directory: a repository of user information, including public-key certificates. Directory connections are opened using the Directory object connect method. A directory with a particular name can have more than one connection open at a time. All DirConnection objects must support all properties and methods listed here, unless otherwise specified.

Note

This object can only be obtained from a Directory object and is thus governed by the security restrictions of the Directory object. The DirConnection object is therefore available only for batch, console and application initialization, including in Adobe Reader. See also Privileged context.

DirConnection properties

canList

Version (Key)

Save-Prefs

Security

Product

Type

Access

6.0

No

Yes

All

Boolean

R

Indicates whether the directory connection is capable of listing all of its entri