Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

Revu supports JavaScript to enhance the capabilities of PDF forms, create interactive stamps and more. This guide is in-depth documentation of all JavaScript capabilities available in Revu. If you are already a seasoned Revu JavaScript developer you may want to jump straight to the API Reference. Otherwise, get started here.

History

VersionDateNotes
0.1UNRELEASEDRelease notes will go here

Copyright © 2025 Bluebeam, Inc. All Rights Reserved

Chapter 1: Getting Started

Background

Hello World

Background

History

JavaScript was invented as part of the Netscape Navigator browser such that web pages could be more interactive. As lore goes, the first version was created in only 10 days! It has stood the test of time and remains as the cornerstone of web development. These days, JavaScript development for the web looks very different than it did nearly 30 years ago. There are numerous advancement such as single page application frameworks, package managers, bundlers, and more that has enabled teams of people to work on complex web applications.

However, PDF JavaScript development is not so different than the way development took place in the early internet. PDF JavaScript for the most part is embedded within indvidual PDF files, and as a developer, rather than pulling in many different pre-existing packages and using build systems, plain JavaScript will need to be written that targets a completely different object model than that of the web.

As the original stewards of the PDF specification, Adobe introduced JavaScript capabilities into Adobe Acrobat in support of interactive form fields. Revu has supported JavaScript since version 6.5 with expanded support in updated versions of Revu over time.

DOMs (Document Object Models)

The only similarity between web and PDF development, is that the core language is the same. Meaning that types such as strings, arrays, and numbers are applicable whether in the web or a PDF. However, the web and PDF have very different document object models. As such, it is imperative that when making internet searches for JavaScript assistance, that you understand when the results are referring to web development that may not be applicable for the PDF JavaScript you are developing.

A document object model connects the core language of JavaScript to the domain of the particular application hosting the script capability. For web, this domain is an HTML web page and its tree of elements. For PDF, the domain is the PDF document with its own collection of PDf specific elements, such as form fields, layers and more. This book documents the complete DOM of Revu as well as dives into using JavaScript in PDF files to make them more interactive for specific workflows.

Contexts

Another key difference between web development and PDF development is where you write your code. In web development, typically you would create a file with the .js extension that lives alongside your HTML file and is published as part of the web page. Addtionally, you would modify the .js file in the code/text editor of your choice.

PDF is different in that snippets of JavaScript are typically embedded throughout the PDF accessed in different areas within Revu directly.

In a later chapter we will go into detail of all the different contexts of which JavaScript can be run from within a PDF file. For now, let's dive straight to a Hello World example.

Hello World

The quickest way to get started with PDF JavaSript is to attach a snippet of JavaScript to the Mouse Up action of a form field button. Executing JavaScript as part of a form field action is one of the primary ways that JavaScript gets executed with a PDF.

Follow these steps to access the JavaScript Editor for a Button

  1. Create a new PDF file
  2. Place a form field button the first page of this new PDF
  3. Access the properties panel and navigate to the Actions sub-section
  4. Click 'add action' with the 'Mouse Up' trigger selected
  5. Click 'edit' found on the Form tab within that dialog

And now with the JavaScript Editor showing, paste in the following:

app.alert('Hello, World!')

Click 'Ok' on all the dialogs, and once back to the main view, press 'escape' to deselect the button. Now try clicking the button and you should see a popup with your 'Hello, World!' string! The app.alert method is one of many Revu specific functions that are available.

Now that you know where to begin with writing JavaScript in Revu, let's dive into the fundamentals of JavaScript before we explore more of the Revu specific functions that are available.

Chapter 2: JavaScript Fundamentals

Fundamentals

JavaScript Fundamentals

Getting Started

JavaScript is a programming language that allows you to add logic and interactivity to your PDF documents. While the previous chapter touched on JavaScript's history, this chapter focuses on the core language features you'll need to write effective scripts in Revu. Think of JavaScript as a set of instructions that tell Revu what to do - whether that's calculating form field values, validating user input, or responding to button clicks.

Comments

Before diving into code, let's start with comments. Comments are notes you write for yourself or other developers that JavaScript ignores when running. They're essential for documenting what your code does.

// This is a single-line comment

/* 
   This is a multi-line comment
   that can span several lines.
   Use it for longer explanations.
*/

Variables and Data Types

Variables are containers that store values you can use throughout your script. In JavaScript, you declare variables using var:

var userName = "John Doe"
var pageCount = 10
var isComplete = false

JavaScript has several fundamental data types:

Strings

Strings represent text and are enclosed in either double quotes or single quotes:

var firstName = "Jane"
var lastName = 'Smith'
var fullName = firstName + " " + lastName  // Results in "Jane Smith"

Common string operations:

var text = "Hello World"
var length = text.length           // 11
var upper = text.toUpperCase()     // "HELLO WORLD"
var lower = text.toLowerCase()     // "hello world"
var partial = text.substring(0, 5) // "Hello"

Numbers

Numbers in JavaScript can be integers or decimals:

var quantity = 42
var price = 19.99
var total = quantity * price  // 839.58

Common number operations:

var x = 10
var y = 3
var sum = x + y         // 13
var difference = x - y  // 7
var product = x * y     // 30
var quotient = x / y    // 3.333...
var remainder = x % y   // 1 (modulo operation)

JavaScript provides the Math object for more complex operations:

var rounded = Math.round(3.7)    // 4
var floored = Math.floor(3.7)    // 3
var ceiling = Math.ceil(3.2)     // 4
var absolute = Math.abs(-5)      // 5
var power = Math.pow(2, 3)       // 8
var squareRoot = Math.sqrt(16)   // 4

Booleans

Booleans represent true or false values:

var isEnabled = true
var isVisible = false
var isGreater = 10 > 5  // true

Arrays

Arrays store ordered lists of values:

var colors = ["red", "green", "blue"]
var firstColor = colors[0]     // "red"
var arrayLength = colors.length // 3

// Adding elements
colors.push("yellow")           // Adds to end
colors.unshift("purple")        // Adds to beginning

// Removing elements
var lastItem = colors.pop()     // Removes and returns last item
var firstItem = colors.shift()  // Removes and returns first item

Objects

Objects store collections of key-value pairs:

var person = {
    name: "Alice",
    age: 30,
    email: "alice@example.com"
}

var personName = person.name    // "Alice"
person.age = 31                 // Updates age
person.city = "Seattle"         // Adds new property

Null and Undefined

These special values represent the absence of a value:

var emptyValue = null      // Explicitly empty
var notYetDefined          // undefined (declared but not assigned)

Operators

Comparison Operators

Used to compare values and return boolean results:

var a = 5
var b = 10

a == b   // false (equal to)
a != b   // true (not equal to)
a < b    // true (less than)
a > b    // false (greater than)
a <= b   // true (less than or equal to)
a >= b   // false (greater than or equal to)

Note the difference between == and ===:

5 == "5"   // true (loose equality, converts types)
5 === "5"  // false (strict equality, checks type and value)

Logical Operators

Used to combine or modify boolean values:

var x = true
var y = false

x && y   // false (AND - both must be true)
x || y   // true (OR - at least one must be true)
!x       // false (NOT - inverts the value)

Control Flow

If Statements

Execute code based on conditions:

var score = 85

if (score >= 90) {
    console.println("Excellent!")
} else if (score >= 70) {
    console.println("Good job!")
} else {
    console.println("Keep practicing")
}

Switch Statements

Useful when comparing a single value against multiple cases:

var day = "Monday"

switch (day) {
    case "Monday":
    case "Tuesday":
    case "Wednesday":
    case "Thursday":
    case "Friday":
        console.println("Weekday")
        break
    case "Saturday":
    case "Sunday":
        console.println("Weekend")
        break
    default:
        console.println("Invalid day")
}

For Loops

Repeat code a specific number of times:

// Count from 0 to 4
for (var i = 0; i < 5; i++) {
    console.println("Count: " + i)
}

// Loop through an array
var items = ["apple", "banana", "orange"]
for (var j = 0; j < items.length; j++) {
    console.println(items[j])
}

While Loops

Repeat code while a condition is true:

var counter = 0
while (counter < 3) {
    console.println("Counter: " + counter)
    counter++
}

Break and Continue

Control loop execution:

// Break exits the loop entirely
for (var i = 0; i < 10; i++) {
    if (i === 5) {
        break  // Stops at 5
    }
    console.println(i)
}

// Continue skips to the next iteration
for (var j = 0; j < 5; j++) {
    if (j === 2) {
        continue  // Skips 2
    }
    console.println(j)  // Prints 0, 1, 3, 4
}

Functions

Functions are reusable blocks of code that perform specific tasks:

// Function declaration
function calculateArea(width, height) {
    return width * height
}

// Using the function
var area = calculateArea(10, 5)  // 50

Functions can also be assigned to variables:

var multiply = function(a, b) {
    return a * b
}

var result = multiply(3, 4)  // 12

Functions don't always need to return values:

function displayMessage(message) {
    console.println("Message: " + message)
    // No return statement
}

displayMessage("Hello")  // Prints but returns undefined

Type Conversion

JavaScript automatically converts types in certain situations, but you can also explicitly convert:

// String to Number
var str = "42"
var num = Number(str)        // 42
var num2 = parseInt(str)     // 42
var float = parseFloat("3.14") // 3.14

// Number to String
var n = 100
var s = String(n)            // "100"
var s2 = n.toString()        // "100"

// To Boolean
var b1 = Boolean(1)          // true
var b2 = Boolean(0)          // false
var b3 = Boolean("text")     // true
var b4 = Boolean("")         // false

Error Handling

Protect your code from errors using try-catch blocks:

try {
    // Code that might cause an error
    var result = riskyOperation()
} catch (e) {
    // Handle the error
    console.println("An error occurred: " + e.message)
}

Scope

Variables have scope, which determines where they can be accessed:

var globalVar = "I'm global"  // Available everywhere

function myFunction() {
    var localVar = "I'm local"  // Only available in this function
    console.println(globalVar)  // Can access global
    console.println(localVar)   // Can access local
}

myFunction()
// console.println(localVar)  // Would cause an error - not accessible here

Best Practices

As you begin writing JavaScript for your PDFs, keep these guidelines in mind:

  1. Use meaningful variable names: Instead of var t = 10, use var pageWidth = 10

  2. Initialize variables: Always give variables an initial value when possible

  3. Be consistent with quotes: Pick either single or double quotes for strings and stick with it

  4. Handle edge cases: Consider what happens if a variable is null or undefined

  5. Keep functions focused: Each function should do one thing well

  6. Comment complex logic: If something isn't immediately obvious, add a comment

  7. Test incrementally: Test your code as you write it, don't wait until everything is done

Common Pitfalls

Watch out for these common mistakes:

// Forgetting var creates a global variable (avoid this)
myVariable = 10  // Bad
var myVariable = 10  // Good

// Comparing with = instead of ==
if (x = 5) {  // This assigns 5 to x
    // Wrong!
}
if (x == 5) {  // This compares x to 5
    // Correct
}

// Forgetting that arrays start at 0
var items = ["first", "second", "third"]
var lastItem = items[3]  // undefined - should be items[2]

Moving Forward

This chapter covered the fundamental building blocks of JavaScript. You now know how to work with different data types, control program flow, and create reusable functions. These concepts form the foundation for everything you'll do with JavaScript in Revu.

In the next chapter, we'll explore where and how you can use these JavaScript fundamentals within your PDF documents, examining the different contexts where Revu executes JavaScript code.

Chapter 3: PDF Specifics

Contexts

Security

Misc

JavaScript Contexts

Overview

JavaScript in Revu executes from three distinct contexts, each with its own purpose and scope:

  1. Event-Level Scripts - Code that runs in response to user actions
  2. Document-Level Scripts - Code that loads when a PDF opens
  3. Folder-Level Scripts - Code stored externally that's available to all PDFs

Understanding where to place your code and what each context can access is fundamental to PDF scripting in Revu.

Event-Level Scripts

Event-level scripts are the most common type of JavaScript in PDF documents. They execute when users interact with form fields, buttons, and other interactive elements.

Accessing Event Scripts

In Revu, you add event scripts through the Properties panel:

  1. Select a form field or button
  2. Open the Properties panel
  3. Navigate to the Actions tab
  4. Choose the trigger event (Mouse Up, On Focus, Validate, etc.)
  5. Select "Run a JavaScript" as the action
  6. Enter your JavaScript code

The 'this' Object

In event-level scripts, this refers to the Doc object of the current PDF:

// In a button's Mouse Up event
console.println(this.numPages)  // Number of pages in the document
var field = this.getField("TextField1")  // Access a form field
this.print()  // Open the print dialog

The 'event' Object

Event scripts have access to a special event object containing information about the current interaction:

// In a text field's Keystroke event
console.println(event.value)  // Current field value
console.println(event.change)  // The keystroke being entered
event.rc = false  // Cancel the event

Document-Level Scripts

Document-level scripts execute automatically when a PDF opens. They're ideal for initialization code and defining functions that will be used throughout the document.

Accessing Document Scripts

In Revu, create document-level scripts through:

  1. Go to Forms > JavaScript
  2. Select "Document JavaScript" from the dropdown
  3. Click "Add" to create a new script
  4. Name your script
  5. Enter your JavaScript code

Purpose

Document-level scripts typically:

  • Define reusable functions for the entire document
  • Initialize form field values
  • Create document-wide variables
  • Set up the document environment

The 'this' Object

In document-level scripts, this also refers to the Doc object:

// Document-level script
console.println("Document: " + this.documentFileName)

// Define a function available to all events in this document
function formatCurrency(value) {
    return "$" + Number(value).toFixed(2)
}

// Initialize a field
this.getField("DateField").value = util.printd("mm/dd/yyyy", new Date())

Scope

Variables and functions defined in document-level scripts are available to all event scripts within that document:

// Document-level script
var taxRate = 0.08

function calculateTax(amount) {
    return amount * taxRate
}
// Any event script in the same document can use these
var tax = calculateTax(100)
console.println("Tax rate is: " + taxRate)

Folder-Level Scripts

Folder-level scripts are JavaScript files stored outside of PDFs, making their functions available to all PDFs opened in Revu.

Location

Folder-level scripts are stored in:

C:\ProgramData\Bluebeam Software\Bluebeam Revu\21\Revu\JavaScript

Any .js file in this directory loads automatically when Revu starts.

Purpose

Folder-level scripts provide:

  • Utility functions used across multiple PDFs
  • Company-wide standards and validations
  • Shared libraries of common functions
  • Trusted functions for privileged operations

The 'this' Object

In folder-level scripts, this is undefined, not a document. To work with documents, you must pass them as parameters:

// Folder-level script (utilities.js)
// 'this' is undefined, not a document

// Global function available to all PDFs
function globalFormatDate(date) {
    return util.printd("yyyy-mm-dd", date)
}

// Function that accepts a [Doc](../chapter_5/Doc.md) object as parameter
function countFieldsInDocument(doc) {
    // Must receive the document explicitly
    return doc.numFields
}

Using folder-level functions from a PDF:

// In a PDF's event script
var formatted = globalFormatDate(new Date())  // Call global function
var fieldCount = countFieldsInDocument(this)  // Pass 'this' (the Doc) explicitly

Context Interaction

The three contexts work together to create complete solutions:

// Folder-level: Define utility
function calculateInterest(principal, rate, time) {
    return principal * Math.pow(1 + rate, time)
}

// Document-level: Add document-specific logic
var defaultRate = 0.05

function getLocalPayment() {
    var amount = this.getField("Amount").value
    return calculateInterest(amount, defaultRate, 5)
}

// Event-level: Use both in response to user action
var payment = getLocalPayment()
this.getField("Result").value = payment

Loading Order

  1. Folder-level scripts load when Revu starts
  2. Document-level scripts load when a PDF opens
  3. Event-level scripts run when triggered

This means folder functions are always available, document functions are available after the PDF loads, and event scripts can use both.

Quick Reference

Where to place code:

  • Folder-level: Shared utilities across multiple PDFs
  • Document-level: PDF-specific functions and initialization
  • Event-level: User interaction responses

How 'this' works:

  • Folder-level: this is undefined
  • Document-level: this is the Doc object
  • Event-level: this is the Doc object

Moving Forward

Understanding these three contexts provides the framework for JavaScript in Revu. The next section explores security.

Security

Overview

JavaScript in PDF documents operates under a security model that protects users from potentially harmful operations. Certain functions are marked as "secure" and can only be executed in trusted contexts.

Secure vs. Non-Secure Functions

Non-Secure Functions - Can be called from any context:

  • Reading form field values
  • Basic calculations
  • Displaying alerts
  • Navigating pages
  • Form manipulations

Secure Functions - Require elevated privileges:

Trust Levels by Context

Event and Document Scripts

Both run in an untrusted context and cannot execute secure functions directly:

// Button event or document script - WILL FAIL
var stream = util.readFileIntoStream("/C/data.txt")  // Security error!

Folder-Level Scripts

Can define trusted functions that execute secure operations:

// Folder-level script - CAN define trusted functions
var trustedReadFile = app.trustedFunction(function(path) {
    app.beginPriv()  // Elevate privileges
    var stream = util.readFileIntoStream(path)
    app.endPriv()    // Return to normal
    return stream
})

This pattern uses app.trustedFunction, app.beginPriv, and app.endPriv to handle secure operations.

Creating Trusted Functions

The pattern for trusted functions:

var myTrustedFunction = app.trustedFunction(function(parameters) {
    app.beginPriv()  // Start privileged block
    
    // Secure operations here
    var result = someSecureOperation()
    
    app.endPriv()    // End privileged block
    return result
})

Key points:

  • Must be defined in folder-level scripts
  • app.beginPriv() and app.endPriv() wrap secure operations
  • Can be called from untrusted contexts

Trust Propagation

Helper functions that need privileges use app.trustPropagatorFunction():

// Helper that needs privileges
var trustedHelper = app.trustPropagatorFunction(function() {
    app.beginPriv()
    var path = app.getPath("user", "documents")
    app.endPriv()
    return path
})

// Main trusted function
var trustedMain = app.trustedFunction(function() {
    app.beginPriv()
    var path = trustedHelper()  // Helper inherits trust
    // Do something with path
    app.endPriv()
})

Alternative Trust Methods

Besides folder-level scripts, trust can be established through:

  1. Trusted Locations: Mark folders as trusted in Revu preferences
  2. Certified PDFs: Digitally signed PDFs with trusted certificates

These are configured through Revu's UI, not JavaScript.

Quick Reference

Establishing trust:

Common secure operations:

  • File I/O
  • System paths
  • URL launching
  • Data import/export

Moving Forward

Understanding trusted functions and the security model enables powerful automation while maintaining safety. Folder-level scripts are the key to bridging the gap between untrusted PDF contexts and secure system operations. Next up we will look at a few more PDF specific concepts you will need.

Miscellaneous Topics

API Calling Conventions

Revu's JavaScript API supports two ways to call functions: positional parameters and named parameters using an object literal. This flexibility allows you to choose the style that best fits your needs.

Positional Parameters

The traditional approach passes parameters in order:

app.alert("My Message", 1, 0, "Warning")

Named Parameters

Alternatively, pass a single object with named properties:

app.alert({
    cMsg: "My Message",
    nIcon: 1,
    nType: 0,
    cTitle: "Warning"
})

Both calls are identical. The parameter names in the object must match exactly those defined in the API (like cMsg, nIcon, etc.). This is why parameter names are precisely specified in the documentation.

Mixed Usage

When using named parameters, you can omit optional parameters more easily:

// Positional - must include placeholders
app.alert("Message", 1, 0, "Title", null, checkboxObj)

// Named - only include what you need
app.alert({
    cMsg: "Message",
    nIcon: 1,
    cTitle: "Title",
    oCheckbox: checkboxObj
})

PDF-Specific Objects

Rectangles

Many PDF operations use rectangle arrays to define areas on a page. A rectangle is an array of four numbers: [left, top, right, bottom].

// Define a rectangle for a form field
var rect = [72, 720, 216, 648]  // 2x1 inch box near top-left

// Add a text field using the rectangle
this.addField("myField", "text", 0, rect)

// Get a field's rectangle
var field = this.getField("myField")
var fieldRect = field.rect  // Returns [left, top, right, bottom]

Important: PDF coordinates start from the bottom-left corner of the page, with Y increasing upward. This is opposite from many graphics systems where Y increases downward.

Colors

Colors in PDF JavaScript are represented as arrays in various color spaces:

// Predefined colors
var red = color.red      // ["RGB", 1, 0, 0]
var blue = color.blue    // ["RGB", 0, 0, 1]

// Custom colors
var gray = ["G", 0.5]                    // Grayscale
var rgb = ["RGB", 0.5, 0.7, 0.3]        // RGB
var cmyk = ["CMYK", 0.1, 0.2, 0.3, 0]  // CMYK

// Using colors
field.fillColor = color.yellow
field.strokeColor = ["RGB", 0.5, 0.5, 0.5]

Spans

Text spans are objects that define formatted text segments:

var spans = [
    { text: "Regular text " },
    { text: "Bold text", fontWeight: 700 },
    { text: " and ", fontStyle: "italic" },
    { text: "colored", textColor: color.red }
]

field.richText = spans

Units and Measurements

Points

Most measurements in PDF JavaScript use points as the unit:

  • 72 points = 1 inch
  • 1 point = 1/72 inch

Common conversions:

// Convert inches to points
function inchesToPoints(inches) {
    return inches * 72
}

// Convert points to inches
function pointsToInches(points) {
    return points / 72
}

// Page dimensions are in points
var pageSize = this.getPageBox()
var widthInPoints = pageSize[2] - pageSize[0]
var widthInInches = widthInPoints / 72

// Standard page sizes in points
// Letter: 612 x 792 (8.5" x 11")
// Legal: 612 x 1008 (8.5" x 14")
// Tabloid: 792 x 1224 (11" x 17")

Working with Measurements

When positioning elements, remember to convert units:

// Position a field 2 inches from left, 3 inches from bottom
var leftInches = 2
var bottomInches = 3
var widthInches = 1.5
var heightInches = 0.5

var rect = [
    leftInches * 72,                          // left
    bottomInches * 72 + heightInches * 72,    // top
    leftInches * 72 + widthInches * 72,       // right
    bottomInches * 72                         // bottom
]

this.addField("myField", "text", 0, rect)

Special Considerations

Page Coordinate System

PDF coordinates differ from typical screen coordinates:

  • Origin (0,0) is at the bottom-left corner
  • Y values increase upward
  • X values increase to the right (standard)
var pageBox = this.getPageBox()  // Returns [0, 0, 612, 792] for letter
// pageBox[0], pageBox[1] = bottom-left (usually 0, 0)
// pageBox[2], pageBox[3] = top-right (width, height in points)

Field Naming

Form fields in PDFs support hierarchical naming using dots:

// Create related fields with hierarchical names
this.addField("address.street", "text", 0, rect1)
this.addField("address.city", "text", 0, rect2)
this.addField("address.zip", "text", 0, rect3)

// Access parent group
var addressFields = this.getField("address")  // Gets all address.* fields

String Encoding

When working with file paths or special characters:

// Use forward slashes for paths, even on Windows
var path = "/C/Users/Documents/file.pdf"  // Correct
// var path = "C:\\Users\\Documents\\file.pdf"  // Avoid

// Device-independent paths start with /
var devicePath = "/C/folder/file.txt"  // Windows C: drive

Quick Reference

Calling styles:

  • Positional: func(param1, param2, param3)
  • Named: func({name1: param1, name2: param2})

Common objects:

  • Rectangle: [left, top, right, bottom] in points
  • Color: ["RGB", r, g, b] or ["CMYK", c, m, y, k]
  • Span: {text: "string", fontWeight: 700}

Key measurements:

  • 72 points = 1 inch
  • Letter page = 612 x 792 points
  • Origin at bottom-left, Y increases upward

Moving Forward

These conventions and objects are foundational to working with PDFs in Revu. Understanding coordinate systems, units, and calling conventions will help you write cleaner, more maintainable code as you build interactive PDF solutions.

Chapter 4: Events

Events

Events

Understanding Events

Events are the heartbeat of interactive PDFs. Every time a user clicks a button, types in a field, or interacts with your document, an event fires. JavaScript code attached to these events brings your PDFs to life.

The event object appears automatically when an event fires - you don't create it or access it through this. It's simply there in your event handler code, containing information about what triggered the event.

Event Flow

Text Field Entry

  1. Focus - User clicks into field
  2. Keystroke - Each character typed (willCommit = false)
  3. Keystroke - Final value (willCommit = true)
  4. Validate - Checks if value is acceptable
  5. Format - Formats for display
  6. Blur - User leaves field
  7. Calculate - Other fields recalculate

For dropdowns and listboxes, the Keystroke event serves as the selection change event:

// Dropdown/List Keystroke event - fires when selection changes
if (event.willCommit) {
    console.println("Selected: " + event.value)
    console.println("Export value: " + event.changeEx)
    
    // React to selection
    if (event.value == "Other") {
        this.getField("OtherText").display = display.visible
    }
}

This is different from text fields - there's no character-by-character keystroke, just the selection change.

Button Click

  1. Mouse Enter - Cursor enters
  2. Mouse Down - Mouse pressed
  3. Mouse Up - Mouse released (primary action event)
  4. Mouse Exit - Cursor leaves

Key Event Properties

Control Properties

event.rc = false     // Cancel the event
event.rc = true      // Allow the event (default)

Value Properties

event.value          // The field value
event.change         // Character being typed (text) or selection (dropdown)
event.changeEx       // Export value for dropdown/list selections
event.willCommit     // Whether action is final

Context Properties

event.target         // Object receiving event
event.source         // Object triggering event
event.targetName     // Name of target field

Common Event Handlers

Validation

// Validate event - check range
if (event.value < 0 || event.value > 100) {
    app.alert("Value must be 0-100")
    event.rc = false
}

Formatting

// Format event - currency
if (event.value != "") {
    event.value = "$" + parseFloat(event.value).toFixed(2)
}

Calculation

// Calculate event - sum fields
var total = 0
for (var i = 1; i <= 3; i++) {
    total += this.getField("Item" + i).value || 0
}
event.value = total

Keystroke Control

// Keystroke event - different behavior for text vs dropdown
if (event.willCommit) {
    // Final value being committed
    console.println("Final: " + event.value)
} else {
    // Text field only - character input
    event.change = event.change.toUpperCase()
}

Special Patterns

Required Fields

// WillSave event
if (!this.getField("Required").value) {
    app.alert("Complete required fields")
    event.rc = false
}

Conditional Visibility

// Dropdown keystroke event
if (event.willCommit && event.value == "Other") {
    this.getField("Details").display = display.visible
} else {
    this.getField("Details").display = display.hidden
}

Input Masking

// Phone number keystroke
if (!event.willCommit) {
    // Only allow digits while typing
    if (!/^\d*$/.test(event.change)) {
        event.rc = false
    }
}

Stamps and Events

Stamps have a unique event structure. The stamp's JavaScript accesses the document through a double-source pattern:

// In stamp JavaScript
var stamp = event.source              // The stamp
var doc = event.source.source         // The document

// Interact with the document
doc.getField("StampDate").value = new Date()
var pageCount = doc.numPages

This event.source.source pattern is essential for stamps that modify the underlying document. Chapter 6 explores complete stamp examples.

Calculation Order

Fields calculate in the order set in Forms > Edit Form Fields > Set Field Calculation Order. This matters when fields depend on each other:

// Field A calculates first
event.value = this.getField("Quantity").value * 10

// Field B calculates second, can use Field A's result
event.value = this.getField("FieldA").value * 1.08

Quick Reference

Event Types:

  • Fields: Focus, Blur, Keystroke (typing or selection), Validate, Format, Calculate
  • Document: Open, WillSave, DidSave, WillPrint, DidPrint
  • Mouse: Up, Down, Enter, Exit
  • Page: Open, Close

Key Patterns:

  • Cancel event: event.rc = false
  • Dropdown change: Keystroke with willCommit = true
  • Character input: Keystroke with willCommit = false
  • Stamp document access: event.source.source

Moving Forward

Events transform static PDFs into dynamic documents. By understanding event flow and choosing the right event for each task, you can create sophisticated forms that respond intelligently to user actions. The detailed property reference in event.md provides complete documentation for all event properties.

Chapter 5: API Reference

app

Bookmark

Collab

Color

console

Data

Doc

event

Field

global

Icon

identity

Net.HTTP

OCG

PrintParams

ReadStream

Span

Template

util

app

app is a static object that represents the Revu application and contains application specific functions and utilities.

properties

focusRect

SecureTypeAccess
NobooleanR/W

Toggles the focus rectangle around form fields on and off

example:

app.focusRect = false

formsVersion

SecureTypeAccess
NonumberR

Exists for compatibility reasons. Always returns 9.0


fullscreen

SecureTypeAccess
NobooleanR

Exists for compatibility reasons. Always returns false


language

SecureTypeAccess
NostringR

Exists for compatibility reasons. Always returns "ENU"


numPlugIns

SecureTypeAccess
NonumberR

Exists for compatibility reasons. Always returns 0


openInPlace

SecureTypeAccess
NobooleanR

Exists for compatibility reasons. Always returns false


platform

SecureTypeAccess
NostringR

Exists for compatibility reasons. Always returns "WIN"


plugIns

SecureTypeAccess
NoarrayR

Exists for compatibility reasons. Always returns an empty array


printerNames

SecureTypeAccess
Noarray of stringsR

List of installed printers. Requires Revu 21.5 or above

example:

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

runtimeHighlight

SecureTypeAccess
NobooleanR/W

Toggles highlighting form fields for improved visibility on and off

example:

app.runtimeHighlight = false // Turn off highlighting form fields

runtimeHighlightColor

SecureTypeAccess
NocolorR/W

The highlight color when highlighting form fields is enabled

app.runtimeHighlight = true
app.runtimeHighlightColor = color.blue

toolbar

SecureTypeAccess
NobooleanR/W

Exists for compatibility reasons. Always returns true


toolbarHorizontal

SecureTypeAccess
NobooleanR/W

Exists for compatibility reasons. Always returns true


toolbarVertical

SecureTypeAccess
NobooleanR/W

Exists for compatibility reasons. Always returns true


viewerType

SecureTypeAccess
NostringR

Exists for compatibility reasons. Always returns "Exchange-Pro"


viewerVariation

SecureTypeAccess
NostringR

Exists for compatibility reasons. Always returns "Full"


viewerVersion

SecureTypeAccess
NonumberR

Exists for compatibility reasons. Always returns 8


viewerVersionRevu

SecureTypeAccess
NonumberR

Returns the current Revu version (i.e. 21.3.0.4216)

The presence of this property is the best way to determine that the PDF is running in the context of Revu.

example:

console.println(app.viewerVersionRevu)

methods

alert

Secure
No

Displays an alert box

alert(cMsg, nIcon, nType, cTitle, oDoc, oCheckbox)

cMsg: The message to be displayed

nIcon: [optional] The icon type

  • 0: Error (default value)
  • 1: Warning
  • 2: Question
  • 3: Status

nType: [optional] The button types

  • 0: OK (default value)
  • 1: OK, Cancel
  • 2: Yes, No
  • 3: Yes, No, Cancel

cTitle: [optional] The alert box title, default is "Bluebeam Revu x64"

oDoc: [optional] The Doc object associated with the alert box. Not used by Revu

oCheckbox: [optional] Checkbox object that results in a checkbox shown in the alert box. Requires Revu 21.5 or above

  • cMsg: [optional] Checkbox string, default is "Do not show this message again"
  • bInitialValue: [optional] Initial state of the checkbox, default is false
  • bAfterValue: State of the checkbox after alert box closes

examples:

app.alert("My Message")
var checkBox = { cMsg: "Suppress going forward", bInitialValue: true }

app.alert("Warning! Something interesting happened", 1, 0, "Warning", this, checkBox)

if (checkBox.bAfterValue) {
    console.println("You wish to suppress this dialog in the future")
} else {
    console.println("You wish to see the warning again")
}

beep

Secure
No

Causes the application to play a sound

app.beep(nType)

nType: [optional] The sounds type

  • 0: Error
  • 1: Warning
  • 2: Question
  • 3: Status
  • 4: Default (default value)

example:

app.beep(2) // Plays the question sound

beginPriv

Secure
Yes

Begins elevated privileges

app.beginPriv()

Elevates the priviledges of the current function so that secure calls can be made until app.endPriv is called. app.beginPriv can only be called within a function that is trusted. See trustedFunction for more information. Used with endPriv and trustPropagatorFunction.


clearInterval

Secure
No

Clears a timer previously set by setInterval.

app.clearInterval(oInterval)

oInterval: Object returned by setInterval


clearTimeOut

Secure
No

Clears a timer previously set by setTimeOut.

app.clearTimeOut(oTime)

oTime: Object returned by setTimeOut


endPriv

Secure
Yes

Ends elevated privileges

app.endPriv()

Returns elevated privilege in a trusted function back to normal such that secure functions can no longer be called. Used in conjunction with app.beginPriv and app.trustedFunction.


execDialog

Secure
No

Displays a custom modal dialog to the user.

app.execDialog(monitor, inheritDialog, parentDoc)

monitor: Object that describes the dialog

inheritDialog: [optional] Dialog object to reuse. Not used by Revu

parentDoc: [optional] Doc object to be used as the parent. Not used by Revu

Returns a string matching an ItemID found in the monitor object

monitor

The monitor parameter is an object literal. Some properties are callback functions that are each called at various points of the lifecycle of the dialog and the description property represents the contents of the dialog.

All callback functions take a single parameter, dialog of type Dialog.

PropertyDescription
initialize[optional] Called when the dialog is initialized
validate[optional] Called when user input needs to be accepted or rejected
commit[optional] Called when the OK button is clicked
destroy[optional] Called when the dialog box is done
...ItemID[optional] ItemID properties called when their element is changed
descriptionObject describing the UI Elements of the dialog

Dialog

A Dialog object is passed into each of the above callbacks and has the following methods.

MethodParameterDescription
enableobjectObject with key/value pairs of ItemID and boolean to enable/disable items.
endstringCloses the dialog passing in the result such as "ok", "cancel", or "other".
loadobjectObject with key/value pairs of ItemID and strings of initial values.
storeNoneReturns on Object with key/value pairs of ItemID and resulting values.

description

The description parameter of the monitor object is also an object literal that describes the UI elements of the dialog.

PropertyTypeDescription
namestringDialog title
first_tabstring[optional] ItemID of first in the tab order. Not used by Revu
widthnumber[optional] Width in pixels. Default is auto-calculated
heightnumber[optional] Height in pixels. Default is auto-calculated
char_widthnumber[optional] Width in characters. Not used by Revu
char_heightnumber[optional] Height in characters. Not used by Revu
align_childrenstring[optional] Alignment for all child elements. See below.
elementsarrayArray of element objects. See below.

align_children

The following are the valid options for align_children

  • "align_left"
  • "align_center"
  • "align_right"
  • "align_top"
  • "align_fill": Stretches across the parent
  • "align_distribute": Distributes horizontally
  • "align_row": Behaves the same as "align_distribute"
  • "align_offscreen": Behaves the same as "align_fill"

elements

The elements parameter of the description object is an array of element objects with the following properties

PropertyTypeDescription
namestringText of this element, ignored by "edit_text"
item_idstringItemID of this element
typestring[optional] Type of UI element. See below.
next_tabstring[optional] ItemID of next in the tab order. Not used by Revu
widthnumber[optional] Width in pixels
heightnumber[optional] Height in pixels
char_widthnumber[optional] Width in characters. Not used by Revu
char_heightnumber[optional] Height in characters. Not used by Revu
fontstring[optional] "default", "dialog", or "palette". Not used by Revu
boldboolean[optional] Specifies bold
italicboolean[optional] Specifies italic
alignmentnumber[optional] Alignment for this element. Same options as align_children above
align_childrennumber[optional] Alignment for all child elements. See above.
elementsarray[optional] Array of child element objects. See below.

type

  • "button": Button
  • "check_box": Checkbox
  • "radio": Radiobutton
  • "list_box": List box
  • "hier_list_box": Tree
  • "static_text": Label
  • "edit_text": Text Box
  • "popup": Combo Box
  • "ok": Ok button
  • "ok_cancel": Ok and Cancel buttons
  • "ok_cancel_other": Ok, Cancel, and Other buttons
  • "view": Container that holds child elements
  • "cluster": Container with a frame that holds child elements
  • "gap": Spacer

There are a few additional properites for element objects dependent on the type

Element TypePropertyTypeDescription
static_textmultilinebooleanEnable multiline for the control.
edit_textmultilinebooleanEnable multiline for the control.
edit_textreadonlybooleanDisable the ability to edit text.
edit_textpasswordbooleanHide the text with asterisks.
edit_textPopupEditbooleanNot used by Revu
edit_textSpinEditbooleanUse text box as a numeric up/down.
radiogroup_idstringGroup radio buttons together.
ok, ok_cancel, ok_cancel_otherok_namestringOverride OK button text.
ok, ok_cancel, ok_cancel_othercancel_namestringOverride Cancel button text.
ok, ok_cancel, ok_cancel_otherother_namestringOverride Other button text.

example:

Document level script:

// Suggestion entry form where a user can choose whether a bug or a feature
var dialogSuggestion = {
    initialize: function(dialog) {
        console.println("initialize")
        // Set to a feature by default
        dialog.load({"rd02": true})
        this.isBug = false
        // Disable bug type because it is a feature by default
        dialog.enable({
            "rd03" : this.isBug,
            "rd04" : this.isBug
        });
    },
    commit: function(dialog) {
        // When the user presses "Ok", this handler will execute first
        console.println("commit")
        var results = dialog.store()

        console.println("Title: " + results["edt1"])
        console.println("Description: " + results["edt2"])
        console.println("Type: " + (results["rd01"] ? "Bug" : "Feature"))
        if (this.isBug) {
            console.println("Bug Type: " + (results["rd03"] ? "New" : "Regression"))
        }
    },
    ok: function(dialog) {
        console.println("Ok")
    },
    rd01: function (dialog) {
        this.toggleIsBug(dialog) // Toggle for changing either Bug or Feature
    },
    rd02: function (dialog) {
        this.toggleIsBug(dialog)
    },
    toggleIsBug: function(dialog) {
        this.isBug = !this.isBug;
        dialog.enable({
            "rd03" : this.isBug,
            "rd04" : this.isBug
        });
        if (!this.isBug) {
            dialog.load({
                "rd03": false,
                "rd04": false 
            })
        }
    },
    cancel: function(dialog) {
        console.println("Cancel")
    },
    description:
    {
        name: "Suggestion",
        elements:
        [
            {
                type: "view",
                align_children: "align_left",
                elements: [
                    {
                        type: "view",
                        align_children: "align_row",
                        elements: [
                            {
                                type: "static_text",
                                name: "Title:",
                                width: 100,
                                height: 20
                            },
                            {
                                type: "edit_text",
                                name: "",
                                item_id: "edt1",
                                width: 200,
                                height: 20
                            }
                        ]
                    },
                    {
                        type: "view",
                        align_children: "align_row",
                        elements: [
                            {
                                type: "static_text",
                                name: "Description:",
                                width: 100,
                                height: 20
                            },
                            {
                                type: "edit_text",
                                name: "",
                                item_id: "edt2",
                                width: 200,
                                height: 100,
                                multiline: true
                            }
                        ]
                    },
                    {
                        type: "view",
                        align_children: "align_row",
                        elements: [
                            {
                                type: "static_text",
                                name: "Type: "
                            },
                            {
                                type: "radio",
                                item_id: "rd01",
                                group_id: "rad0",
                                name: "Bug"

                            },
                            {
                                type: "radio",
                                item_id: "rd02",
                                group_id: "rad0",
                                name: "Feature",
                            }
                        ]
                    },
                    {
                        type: "view",
                        align_children: "align_row",
                        elements: [
                            {
                                type: "static_text",
                                name: "Bug Type: "
                            },
                            {
                                type: "radio",
                                item_id: "rd03",
                                group_id: "rad1",
                                name: "New"

                            },
                            {
                                type: "radio",
                                item_id: "rd04",
                                group_id: "rad1",
                                name: "Regression",
                            }
                        ]
                    }
                ]
            },
            {
                type: "gap",
                height: 10
            },
            {
                type: "ok_cancel"
            }
        ]
    }
};

Button event:

app.execDialog(dialogSuggestion)

execMenuItem

Secure
No

Executes a menu item. The only command supported by Revu is "SaveAs".

app.execMenuItem(cCommand)

cCommand: command to execute

example:

app.execMenuItem("SaveAs")

getPath

Secure
Yes

Returns specfic paths based on a category and requested folder type

app.getPath(cCategory, cFolder)

cCategory: [optional] category of requested folder

  • "app": application level folders (default value)
  • "user": user level folders

cFolder: [optional] particular folder

  • "javascript": app level JavaScript folder (applicable only for "app")
  • "stamps": stamp folder (applicable only for "app")
  • "root": user's preference folder (default value, applicable only for "user")
  • "documents": user's "My Documents" folder (applicable only for "user")

example:

console.println(app.getPath("app", "javascript"))

which prints the following:

/C/ProgramData/Bluebeam Software/Bluebeam Revu/21/Revu/JavaScript


goBack

Secure
No

Navigates backward

app.goBack()

Navigates the user to the previous view in the view stack. This is equivalent of a user clicking the 'Previous View' button in Revu.

example:

var button = this.getField("backButton")
if (!button) // Check if button exists already
{
    var aRect = this.getPageBox()
    var width = aRect[2] - aRect[0]
    var height = aRect[1] - aRect[3]
    rect = [width / 2 - 40, 
            height - 36, 
            width / 2 + 40, 
            height - 15] // Button is 80x21
    button = this.addField("backButton", "button", 0, rect)
    button.fillColor = color.ltGray
    button.strokeColor = color.black
    button.borderStyle = border.b
    button.buttonSetCaption("Back")             
    button.setAction("MouseUp", "app.goBack()")
}

This example creates a back navigation button. This could be a document level script which would run when the PDF opens. It checks to see if the back button exists, and if not it creates one. This example could be expanded to loop over all pages in a document to create a button per page.


goForward

Secure
No

Navigates forward

app.goForward()

Navigates the user to the next view in the view stack. This is equivalent of a user clicking the 'Next View' button in Revu.

See app.goBack for a relevant example


launchURL

Secure
Yes

Launches a URL as a WebTab in Revu

app.launchURL(cURL, bNewFrame)

cURL: URL to launch

bNewFrame: [optional] Specifies whether to create a new window, default is false. Not used by Revu

When called from an untrusted context, LaunchURL will prompt the user with a security warning and they must click 'Allow' for the URL to launch.

example

app.launchURL("www.bluebeam.com")

mailMsg

Secure
No

Sends an e-mail using the default e-mail program configured with MAPI

app.mailMsg(bUI, cTo, cCc, cBcc, cSubject cMsg)

bUI: Specifies whether to show the e-mail window before sending. Revu ignores this value acting as though it is always true.

cTo: [optional] List of e-mail addresses separated by semicolons

cCC: [optional] List of CC addresses separated by semicolons

cBcc: [optional] List of BCC addresses separated by semicolons

cSubject: [optional] Subject line of e-mail

cMsg: [optional] Message body of e-mail

example:

app.mailMsg(true, "support@bluebeam.com", "". "", "Subject", "Message")

openDoc

Secure
No

Opens a PDF document and returns the corresponding Doc object.

app.openDoc(cPath, oDoc, cFS, bHidden, bUseConv, cDest)

cPath: Device-independent path to the PDF file to open.

oDoc: [optional] Doc object used to resolve relative paths. Default is null.

cFS: [optional] Only the empty string is supported, which specifies that the path is to a file on the local file system. Default is "".

bHidden: [optional] Specifies whether or not to open the file as a tab in Revu. Default is false.

bUseConv: [optional] Revu ignores this value acting as though it is always false

cDest: [optional] Named destination (known as a 'Place' in Revu), specifying a location in the PDF file to navigate to.

example:

var doc = app.openDoc("/c/path/to/my/file.pdf")

popUpMenu

Secure
No

Displays a Popup menu to the user. Note: popUpMenuEx is the preferred method for showing Popup menus.

app.popUpMenu(...items)

items: Can be either strings or Arrays. If the parameter is a string, the result is a menu item with that value. "-" is a special case that represents a separator. If the parameter is an Array, a sub-menu is created where the first element in the array is the parent node, and the remaining elements are the sub-menu. Arrays can be nested further.

Returns the menu item selected by the user

simple example:

var selection = app.popUpMenu("Menu Item")

nested example:

var selection = app.popUpMenu(
    "Node 1",
    "-",
    ["Node 2", "Child 1", "Child 2"],
    ["Node 3", "Child 3", "Child 4"]
)

popUpMenuEx

Secure
No

Requires Revu 21.5 or above

Displays a Popup menu to the user.

app.popUpMenuEx(...items)

items: One or more MenuItem objects.

Returns the cReturn parameter of the selected item, or null if no item was selected.

example:

// Loosely equivalent to the popUp example, but also showing bMarked and cReturn
var selection = app.popUpMenuEx(
    {cName: "Node 1"},
    {cName: "-"},
    {cName: "Node 2", oSubMenu: 
        [
            {cName: "Child 1", bMarked: true, cReturn: "C1"},
            {cName: "Child 2", cReturn: "C2"}
        ]
    },
    {cName: "Node 3", oSubMenu: 
        [
            {cName: "Child 3", cReturn: "C3"},
            {cName: "Child 4", cReturn: "C4"}
        ]
    }
)
app.alert(selection)

response

Secure
No

Displays a dialog box prompting the user with a question and an input box.

app.response(cQuestion, cTitle, cDefault, bPassword, cLabel)

cQuestion: The question.

cTitle: [optional] Dialog box title.

cDefault: [optional] Default value for the answer. Default is ""

bPassword: [optional] If true, hides the users reponse with asterisk characters. Default is false

cLabel: [optional] Label before the input box. Default is ""

Returns a string with the user's reponse. If the clicks cancel, null will be returned.

example:

var response = app.response({
    cQuestion: "What is your name?",
    cTitle: "Enter Name",
    cDefault: "John Doe",
    cLabel: "Name"
})
if (response != null)
    app.alert("Your name is " + response)

setInterval

Secure
No

Sets a JavaScript expression to run at specific time intervals.

app.setInterval(cExpr, nMilliseconds)

cExpr: JavaScript expression to run

nMilliseconds: Time interval in milliseconds

Returns an object that can be used when calling clearInterval

example:

// Goes in a document level script
// Moves the button back and forward on the screen until the user clicks the button

var forward = true

function callback() {
    var b = this.getField("movingButton")
    var rect = b.rect
    if (forward && rect[2] < 602) { // Because 8.5 inches is 612 points
        rect[0] += 10
        rect[2] += 10
        b.rect = rect
    } else {
        forward = false
    }

    if (!forward && rect[0] > 10) {
        rect[0] -= 10
        rect[2] -= 10
        b.rect = rect
    } else {
        forward = true
    }
}

var aRect = this.getPageBox()
var width = aRect[2] - aRect[0]
var height = aRect[1] - aRect[3]
rect = [width / 2 - 40, 
        height - 36, 
        width / 2 + 40, 
        height - 15] // Button is 80x21
var button = this.addField("movingButton", "button", 0, rect)
button.fillColor = color.ltGray
button.strokeColor = color.black
button.borderStyle = border.b
button.buttonSetCaption("Stop Me!")             
button.setAction("MouseUp", "app.clearInterval(intervalObj)")

var intervalObj = app.setInterval("callback()", 100)

setTimeOut

Secure
No

Sets a JavaScript expression to run after a set time elapses. Similar to setInterval with the difference that the expression only runs once.

app.setTimeOut(cExpr, nMilliseconds)

cExpr: JavaScript expression to run

nMilliseconds: Time interval in milliseconds

Returns an object that can be used when calling clearTimeOut

example:

var timeoutObj = app.setTimeOut("app.alert('I was set to go 5 seconds ago')", 5000)

trustedFunction

Secure
No

Establishes trust for a function in a folder level script to be able to have secure code that can be called from untrusted contexts.

trustedFunction(oFunc)

oFunc: Function to trust

Certain functions, such as util.readFileIntoStream, must be run securely. Arbitrary PDF files of unknown origin should not be able to ready the contents of files off disk. There are 3 ways to be able to safely execute these secure functions.

  1. Trust a specific file or folder in Revu preferences
  2. Trust certified PDF files in Revu preferences
  3. Mark functions in folder level scripts as trusted

trustedFunction corresponds to method 3 in the above list. trustedFunction is used in conjunction with beginPriv, endPriv, and trustPropagatorFunction so that PDFs regardless of where they are stored are able to call secure functions.

A use case for using trustedFunction would be an organization that wants to push out a company specific JavaScript library of secure code across their organization by rolling out a .js file to the app level JavaScript folder of each users computers, and then embed JavaScript in PDF files that call into functions inside this JavaScript library. For reference, the app level folder is: C:\ProgramData\Bluebeam Software\Bluebeam Revu\21\Revu\JavaScript

A function that calls secure code would be passed into trustedFunction, and then within that function any secure blocks would need to be wrapped between calls of app.beginPriv and app.endPriv. If there are intermediate helper functions that call secure code, then app.trustPropogatorFunction must be used to mark that the helper functions should inherit any trust granted by a function that was passed into trustedFunction.

example:

Folder level JavaScript:

trustedReadFile = app.trustedFunction(function(path) {
    app.beginPriv()
    var s = util.readFileIntoStream(path)
    app.endPriv()
    return s
})

MouseUp button JavaScript:

var stream = trustedReadFile("/path/to/my/file.txt") // Your path would be here
var contents = util.stringFromStream(stream)
app.alert(contents)

See that the mouse up handler is calling the secure function trustedReadFile found in the folder level script. Without calling trustedFunction and using beginPriv/endPriv, there would be a security error.


trustPropagatorFunction

Secure
No

Cascades trust when helper functions are called from trusted functions. See trustedFunction

app.trustPropagatorFunction(oFunc)

oFunc: Function that should inherit trust

example:

trustedHelper = app.trustPropagatorFunction(function() {
    app.beginPriv()
    // Secure code
    app.endPriv()
})

trustedFunction = app.trustedFunction(function() {
    app.beginPriv()
    trustedHelper()
    app.endPriv()
})

objects

Object that represents the parameters of popUpMenuEx. The object has the following properties:

cName: Menu item name. "-" is used to specify a separator.

bMarked: [optional] Boolean specifying if the item is checked

bEnabled: [optional] Boolean specifying if the item is enabled

cReturn: [optional] String specifying the return value if the item is selected. Default is cName

oSubMenu: [optional] A MenuItem object or array of MenuItem objects representing a submitem


Bookmark

Requires Revu 21.5 or above

Bookmark is an object that represents a bookmark in the Bookmarks Tab in Revu. See doc.bookmarkRoot to access the root bookmark node.

properties

children

SecureTypeAccess
NoarrayR

Returns an array of Bookmark objects representing the children of the bookmark. If there are no children, null is returned.

example:

function PrintBookmark(bookmark, indent) {
    console.println(indent + bookmark.name)
    var children = bookmark.children
    if (children)
        children.forEach(c => { PrintBookmark(c, indent + " ") })
}

PrintBookmark(this.bookmarkRoot, "")

color

SecureTypeAccess
NoarrayR/W

Color array specifying the bookmark's text color.

example:

this.bookmarkRoot.children[0].color = color.red

doc

SecureTypeAccess
NoobjectR

The Doc that contains the bookmark.


name

SecureTypeAccess
NostringR/W

The text of the bookmark. See children for an example.


open

SecureTypeAccess
NobooleanR/W

Specifies whether or not to show the bookmark collapsed in the tree.

example:

this.bookmarkRoot.children[0].open = false

parent

SecureTypeAccess
NoobjectR

The Bookmark object of the parent of the bookmark. If the bookmark is the root, then the parent is null.


style

SecureTypeAccess
NonumberR/W

Text style of the bookmark

  • 0: Normal
  • 1: Italic
  • 2: Bold
  • 3: Bold-italic
this.bookmarkRoot.children[0].style = 2 // Bold

methods

createChild

Secure
No

Creates a new bookmark

createChild(cName, cExpr, nIndex)

cName: The text of the new bookmark

cExpr: [optional] JavaScript expression to run when the bookmark is clicked. Default is ""

nIndex: [optional] The 0-based index into the children array. Default is 0

example:

this.bookmarkRoot.createChild("Click Me!", "app.alert('I was clicked')", 0)

execute

Secure
No

Invokes the action of the bookmark

execute()

example:

this.bookmarkRoot.children[0].execute()

insertChild

Secure
No

Moves an existing Bookmark to be a child of this bookmark.

insertChild(oBookmark, nIndex)

oBookmark: The existing Bookmark to move

nIndex: [optional] The 0 based index into the children array. Default is 0


remove

Secure
No

Removes this bookmark and all its children

remove()

example:

this.bookmarkRoot.remove() // Removes all bookmarks

setAction

Secure
No

Sets the bookmark action to the JavaScript expression

setAction(cScript)

cScript: JavaScript expression to run when the bookmark is clicked.

this.bookmarkRoot.children[0].setAction("app.alert('I was clicked')")

Collab

Collab is a static object that primarily provides functionality for managing state models. The custom status feature in Revu uses JavaScript behind the scenes to populate the new states so that custom statuses are compatible with other PDF applications.

properties

user

SecureTypeAccess
NostringR

Login username of the current user. See identity.name for the username as entered in the Revu preferences.


methods

addStateModel

Secure
No

Adds a new state model

Collab.addStateModel(cName, cUIName, oStates, cDefault, bHidden, bHistory)

cName: Unique identifier for the state model

cUIName: Text of the state model as seen by the user

oStates: States object which describes the states in the model

cDefault: [optional] The default state to use. The default is no state

bHidden: [optional] Option to hide the state model. Not used by Revu

bHistory: [optional] Option to maintain the audit history. Not used by Revu

example:

Collab.addStateModel(
    {
        cName: "SimpleStateModel",
        cUIName: "Simple",
        oStates: { 
            "Open": { cUIName: "Open" },
            "Closed": { cUIName: "Closed" } 
        },
        cDefault:"Open"
    }
)

removeStateModel

Secure
No

Removes a state model

Collab.removeStateModel(cName)

cName: Unique identifier for the state model

example:

Collab.removeStateModel("SimpleStateModel")

objects

States

Object that represents the oStates parameter of addStateModel. The keys on the object are unique identifiers for each state, and the values are objects with the following property:

cUIName: Text of the state as seen by the user

example:

var states = { 
    "Open": { cUIName: "Open" },
    "Closed": { cUIName: "Closed" } 
}

color

Colors are represented by arrays where the first element is the colorspace and the remaining elements are the values of each color component. Each value is a number between 0 and 1.

For example ["RGB", 0, 1, 0 ] represents the color blue. Invalid arrays are interpreted as black.

ColorspaceStringComponents
Transparent"T"0
Gray"G"1
RGB"RGB"3
CMYK"CMYK"4

properties

PropertyEquivalent Array
transparent[ "T" ]
black[ "G", 0 ]
white[ "G", 1 ]
red[ "RGB", 1, 0, 0 ]
green[ "RGB", 0, 1, 0 ]
blue[ "RGB", 0, 0, 1 ]
cyan[ "CMYK", 1, 0, 0, 0 ]
magenta[ "CMYK", 0, 1, 0, 0 ]
yellow[ "CMYK", 0, 0, 1, 0 ]
dkGray[ "G", 0.25 ]
gray[ "G", 0.5 ]
ltGray[ "G", 0.75 ]

example:

this.getfield("textBox").textColor = color.red

methods

convert

Secure
No

Converts a color between colorspaces.

color.convert(array, cColorSpace)

array: Color array (see above)

cColorSpace: Target colorspace

Returns color array in the target colorspace.

example:

var cmykGreen = color.convert(color.green, "CMYK")
console.println(cmykGreen) // Displays CMYK,1,0,1,0

equal

Secure
No

Compares color arrays, even across colorspaces.

color.equal(array1, array2)

array1: First color array

array2: Second color array

Returns boolean indicating whether or not the colors are equivalent.

example:

var result = color.equal(color.blue, ["RGB", 0, 0, 1]);
console.println(result) // Displays true

console

console is a static object that interacts with the JavaScript console in Revu for displaying debug messages

methods

clear

Secure
No

Clears the console of all debug messages

console.clear()

example:

console.clear()

hide

Secure
No

Hides the JavaScript console in the user interface

console.hide()

example:

console.hide()

println

Secure
No

Outputs a debug message in the JavaScript console

console.println(cMessage)

cMessage: Debug message to output

console.println("Debug message")

show

Secure
No

Shows the JavaScript console in the user interface

console.show()

example:

console.show()

Data

Data objects represent embedded files within the PDF.

See doc.dataObjects

properties

creationDate

SecureTypeAccess
NodateR

The creation date of the embedded file.


description

SecureTypeAccess
NostringR

The description of the embedded file.


MIMEType

SecureTypeAccess
NostringR

The MIME type of the embedded file.


modDate

SecureTypeAccess
NodateR

The modification date of the embedded file.


name

SecureTypeAccess
NostringR

The name of the embedded file.

example:

this.dataObjects.forEach(d => { console.println(d.name) })

path

SecureTypeAccess
NostringR

The filename with the extension of the embedded file.


size

SecureTypeAccess
NonumberR

The size in bytes of the embedded file.


Doc

Doc object represents the PDF file and is the means by which the majority of JavaScript functionality in Revu is accessed apart from app. There are a number of ways to access Doc, the most common of which is that this is bound to the active Doc in most contexts. Additionally, a number of functions return Doc objects such as extractPages. The Doc object is also available through events.

example:

console.println(this.author) // 'this' is the active Doc

properties

author

SecureTypeAccess
NostringR/W

The author of the document stored in file properties.

author is deprecated

The recommended way to access author is through the info property


baseURL

SecureTypeAccess
NostringR/W

The base URL of the document used to resolve relative links when executing hyperlink actions.

this.baseURL = "https://www.bluebeam.com/"
// Any relative hyperlink will now be referenced from https://www.bluebeam.com

bookmarkRoot

SecureTypeAccess
NoobjectR

Returns a Bookmark object representing the root bookmark in the PDF file.


calculate

SecureTypeAccess
NobooleanR/W

Specifies whether or not form field calculations should be run. Turning off calculations while manipulating lots of form fields can be a performance optimization.


creationDate

SecureTypeAccess
NoDateR

The creationDate of the document stored in file properties.

creationDate is deprecated

The recommended way to access creationDate is through the info property


creator

SecureTypeAccess
NostringR

The creator of the document stored in file properties, for example "Bluebeam Revu"

creator is deprecated

The recommended way to access creator is through the info property


dataObjects

SecureTypeAccess
NoarrayR

Array of Data objects which represent embedded files in the PDF.

example:

this.dataObjects.forEach(d => { console.println(d.name) })

delay

SecureTypeAccess
NobooleanR/W

Exists for compatibility reasons. Always returns false


dirty

SecureTypeAccess
NobooleanR/W

Specifies whether the document needs to be saved


disclosed

SecureTypeAccess
NobooleanR/W

Exists for compatibility reasons. Always returns false


docID

SecureTypeAccess
NoarrayR/W

Array of two strings that are hex-encoded binary. The first string is a permanent ID associated with the PDF file. The second string is an ID that updates upon each save.


documentFileName

SecureTypeAccess
NostringR

The filename of the PDF with the extension.


dynamicXFAForm

SecureTypeAccess
NobooleanR

Exists for compatibility reasons. Always returns false


external

SecureTypeAccess
NobooleanR

Exists for compatibility reasons. Always returns false


filesize

SecureTypeAccess
NonumberR

The size of the PDF file in bytes.


hidden

SecureTypeAccess
NobooleanR

When true the PDF file is open silently in the background and not loaded in a tab.


icons

SecureTypeAccess
NoarrayR

Array of Icon document level icon objects. If there are no icons, null is returned.

example:

if (this.icons != null)
    this.icons.forEach(i => { console.println(i.name) })

info

SecureTypeAccess
NoobjectR

Object that provides access to the key/value file properties in the PDF.

Predefined keys:

  • Title
  • Author
  • Subject
  • Keywords
  • Creator
  • Producer
  • CreationDate
  • ModDate
  • Trapped

Custom keys can be used as well.


innerAppWindowRect

SecureTypeAccess
NoarrayR

Rectangle representing the bounds of the Revu application minus the title bar.

array is in the form of [x, y, width, height].

var rect = this.innerAppWindowRect // returns [0, 24, 2560, 1550]

innerDocWindowRect

SecureTypeAccess
NoarrayR

Returns the same value as innerAppWindowRect.


keywords

SecureTypeAccess
NostringR/W

The keywords of the document stored in file properties.

keywords is deprecated

The recommended way to access keywords is through the info property


layout

SecureTypeAccess
NostringR/W

The page layout of the PDF file.

Valid values:

  • "SinglePage"
  • "OneColumn"
  • "TwoColumnLeft"
  • "TwoColumnRight"
  • "TwoPageLeft"
  • "TwoPageRight"

example:

this.layout = "TwoColumnLeft"

modDate

SecureTypeAccess
NodateR

The modified date of the document stored in file properties.

modDate is deprecated

The recommended way to access modDate is through the info property


mouseX

SecureTypeAccess
NonumberR

The X coordinate of the mouse in PDF space.

example:

function printMouse() {
    console.clear()
    console.println("x: " + this.mouseX + "   y: " + this.mouseY)
}

var obj = app.setInterval("printMouse()", 100)

mouseY

SecureTypeAccess
NonumberR

The Y coordinate of the mouse in PDF space. See mouseX for an example.


numFields

SecureTypeAccess
NonumberR

Total number of form fields in the PDF.


numPages

SecureTypeAccess
NonumberR

Total number of pages in the PDF.


numTemplates

SecureTypeAccess
NonumberR

Total number of Template objects in the PDF.

numTemplates is deprecated

The recommended way to access the number of templates is through the templates property


path

SecureTypeAccess
NostringR

Device-independent path of the PDF file.

example:

console.println(this.path) // Might return /c/path/to/my/file.pdf

outerAppWindowRect

SecureTypeAccess
NoarrayR

Rectangle representing the complete bounds of the Revu application.

array is in the form of [x, y, width, height].

var rect = this.outerAppWindowRect // returns [-18,-18, 2560, 1550]

outerDocWindowRect

SecureTypeAccess
NoarrayR

Returns the same value as outerAppWindowRect.


pageNum

SecureTypeAccess
NonumberR/W

Index of the active page in Revu (0-based)

example:

this.pageNum++ // Navigate to the next page

pageWindowRect

SecureTypeAccess
NoarrayR

Rectangle representing the PDF display bounds within the Revu application.

array is in the form of [x, y, width, height].

var rect = this.pageWindowRect

permStatusReady

SecureTypeAccess
NobooleanR

Exists for compatibility reasons. Always returns true


producer

SecureTypeAccess
NostringR

The producer of the document stored in file properties.

producer is deprecated

The recommended way to access producer is through the info property


requiresFullSave

SecureTypeAccess
NobooleanR

True if the PDF file does not yet exist on disk.


securityHandler

SecureTypeAccess
NostringR

Specifies the security handler if the PDF file is encrypted. Returns null if the file is unencrypted. Revu only supports the "Standard" security handler.


subject

SecureTypeAccess
NostringR/W

The subject of the document stored in file properties.

subject is deprecated

The recommended way to access subject is through the info property


templates

SecureTypeAccess
NoarrayR

Array of Template objects.

example:

this.templates.forEach(t => { console.println(t.name) })

title

SecureTypeAccess
NostringR/W

The title of the document stored in file properties.

title is deprecated

The recommended way to access title is through the info property


URL

SecureTypeAccess
NostringR

URL of the PDF file. If the file is in Studio Projects for instance, it will return a web URL. If a local file, the URL will be prefixed with file:///


zoom

SecureTypeAccess
NonumberR/W

Zoom level of the PDF file as a percentage. 100 equals 100%.

example:

this.zoom = 50 // Set the zoom to 50%

zoomType

SecureTypeAccess
NostringR/W

Zoom type of the PDF file.

Zoom types and corresonding constants that can be used:

Zoom typeConstant
"NoVary"zoomtype.none
"FitPage"zoomtype.fitP
"FitWidth"zoomtype.fitW
"FitHeight"zoomtype.fitH
"Preferred"zoomtype.pref

example:

this.zoomType = zoomtype.fitP // Fit to the page

methods

addField

Secure
No

Adds a form field to the PDF file.

addField(cName, cFieldType, nPageNum, oCoords)

cName: Name of the new field. Can denote a heirarchy by using dots to separate the names. i.e. "parent.child"

cFieldType: Type of the new field. See valid types below.

nPageNum: 0-based page index to add the new field to.

oCoords: Array of 4 numbers specifying the rectangle for the field. The rectangle is in the form of [upper-left-x, upper-left-y, lower-right-x, lower-right-y].

Returns the new Field.

cFileType values:

  • "text"
  • "button"
  • "combobox"
  • "listbox"
  • "checkbox"
  • "radiobutton"
  • "signature"

see app.goBack for a complete example.

example:

this.addField("myTextBox", "text", 0, [100, 100, 200, 80])

addIcon

Secure
No

Adds a document level icon to the PDF file.

addIcon(cName, icon)

cName: Name of the new icon.

icon: Icon object to add.


bringToFront

Secure
No

Sets an open document to be the active tab in Revu.

bringToFront()


calculateNow

Secure
No

Triggers all form field calculations to take place at once. Commonly used in conjunction with the calculate property to temporarily turn off calculations, make a number of modifications programatically, then force calculations to run when done.

calculateNow()

example:

this.calculate = false

// Lots of form field modifications

this.calculate = true
this.calculateNow()

closeDoc

Secure
No

Closes the active document with the option to prompt the user to save any unsaved changes.

closeDoc(bNoSave)

bNoSave: [optional] When true, the file will close without saving. When false, the user will be prompted to save if there are unsaved changes. Default is false.

example:

this.closeDoc(true) // Would cause the file to close, losing any unsaved changes

createDataObject

Secure
No

Creates a new Data object.

createDataObject(cName, cValue, cMIMEType, cCryptFilter)

cName: Name of the data object

cValue: Data to be embedded

cMIMEType: [optional] MIME type of the data object. Default is "text/plain"

cCryptFilter: [optional] Not used by Revu

example:

this.createDataObject("NewFile.txt", "Data to embed")

deletePages

Secure
No

Deletes pages from the PDF file.

deletePages(nStart, nEnd)

nStart: [optional] 0-based index of the first page in the range to delete. Default is 0

nEnd: [optional] 0-based index of the last page in the range to delete. Default is nStart

Returns true if the pages were successfully deleted.

example:

this.deletePages() // Deletes the first page

this.deletePages({nStart: 2, nEnd: 3}) // Deletes pages 2 and 3 (0-based)

exportAsFDF

Secure
Yes

Exports form field data as FDF

exportAsFDF(bAllFields, bNoPassword, aFields, bFlags, cPath, bAnnotations)

bAllFields: [optional] Not used by Revu

bNoPassword: [optional] When true, omit exporting any fields marked as a password. Default is true

aFields: [optional] String array of names of form fields to export, or a string of a single name. When null, all fields will be exported. Default is null.

bFlags: [optional] Not used by Revu

cPath: [optional] The device-independent path of the output FDF file. When supplied, this function requires elevated permissions. Default is null

bAnnotations: [optional] When true, export annotations in addition to the form fields. Default is true

example:

// Export all fields (except those with that are password)
this.exportAsFDF(true, true, null) 

// Exports particular fields to a specific file, requires elevated permissions
this.exportAsFDF(true, true, ['field1', 'field2'], true, '/c/path/to/my/file.fdf') 

exportDataObject

Secure
No

Exports the data object to a local file. exportDataObject no longer requires elevated permissions because cDIPath is no longer supported.

exportDataObject(cName, cDIPath, bAllowAuth, nLaunch)

cName: The name of the data object.

cDIPath: [optional] No longer supported. Function always fails if cDIPath is supplied.

bAllowAuth: [optional] Not used by Revu

nLaunch: [optional] Launch mode, see below:

nLaunch values:

ValueDescription
0Saved to user chosen location and not opened
1Saved to user chosen location and opened
2Saved to a temporary location and opened

example:

// Saved to a temp location and opened
this.exportDataObject("myAttachment.pdf", null, false, 2)

extractPages

Secure
Yes

Extracts pages into a new PDF file.

extractPages(nStart, nEnd, cPath)

nStart: [optional] 0-based index of the first page in the range to extract. Default is 0

nEnd: [optional] 0-based index of the last page in the range to extract. Default is nStart

cPath: [optional] The device-independent path of the output PDF file. When supplied, this function requires elevated permissions. Default is null

Returns a Doc object of the newly created document if cPath is null, otherwise returns null.

example:

this.extractPages() // Extracts the first page and opens a a new file

this.extractPages(1, 2) // Extracts the pages 2 and 3 and opens as a new file

flattenPages

Secure
No

Embeds all annotations directly into the page content making them no longer interactive.

flattenPages(nStart, nEnd, nNonPrint)

nStart: [optional] 0-based index of the first page in the range to flatten. Default is 0

nEnd: [optional] 0-based index of the last page in the range to flatten. Default is nStart, if nStart is supplied, otherwise, the default is the last page of the file.

nNonPrint: [optional] Not used by Revu

example:

this.flattenPages() // Flattens all pages in the file

this.flattenPages(1) // Flattens just the 2nd page in the file

getAnnots3D

Secure
No

Returns a Annot3D object with the single property of activated. Exists for compatibility reasons, 3D Annotation JavaScript is not supported by Revu.

getAnnots3D(nPage)

nPage: 0-based index of the page in the file


getDataObject

Secure
No

Returns a specific Data object associated with the supplied name.

getDataObject(cName)

cName: Name of the Data object to return

Returns a Data object.

example:

var data = this.getDataObject("data.txt")
console.println(data.size)

getDataObjectContents

Secure
No

Returns a stream to the file contents of the Data object.

getDataObjectContents(cName, bAllowAuth)

cName: Name of the Data object.

bAllowAuth: [optional] Not used by Revu

Returns a ReadStream object.

example:

var stream = this.getDataObjectContents("data.txt")
var text = util.stringFromStream(stream, "utf-8")
console.println(text)

getField

Secure
No

Returns a Field object associated with the supplied name.

getField(cName)

cName: Name of the form field.

Returns a Field object.

example:

var f = this.getField("MyField")

getIcon

Secure
No

Returns an Icon object associated with the supplied name.

getIcon(cName)

cName: Name of the icon

Returns an Icon object.

example:

var icon = this.getIcon("MyIcon")
var field = this.getField("button")
field.buttonSetIcon(icon)

getNthFieldName

Secure
No

Returns the name of the field in the file with index of n. See numFields.

getNthFieldName(nIndex)

nIndex: Index of the field

Returns the name of the field

example:

// Prints all field names in the file
for (var n = 0; n < this.numFields; n++)
    console.println(n + ": " + this.getNthFieldName(n))

getNthTemplate

Secure
No

Returns the name of the template in the file with index of n.

getNthTemplate is deprecated

The recommended way to access templates is through the templates property.

getNthTemplate(nIndex)

nIndex: Index of the template

Returns the name of the template


getOCGs

Secure
No

Returns an array of OCG objects for the specified page. Note that OCGs (Optional Content Groups) are referred to as Layers within Revu.

getOCGs(nPage)

nPage: [optional] The 0-based page number to constrain the returned OCGs. If no page number is specified, all OCGs in the file are returned.

Returns an array of OCG objects. If there are no OCGs, null is returned.

example:

var ocgArray = this.getOCGs() // Get all OCGs in file
if (ocgArray != null) {
    ocgArray.forEach(o => { console.println(`Name: ${o.name} State: ${o.state}`) })
}

getPageBox

Secure
No

Returns a rectangle for the specified page box. See the Page Setup feature in Revu.

getPageBox(cBox, nPage)

cBox: [optional] The type of page box. The default is Crop. See below for the full list.

nPage: [optional] The 0-based page number. The default is 0.

The following are the valid options for cBox:

  • "Art"
  • "Bleed"
  • "BBox"
  • "Crop"
  • "Media"
  • "Trim"

Returns an array of numbers specifying the rectangle.

example:

var rect = this.getPageBox("Crop")
var width = rect[2] - rect[0]
var height = rect[1] - rect[3]

console.println(`Width: ${width} Height: ${height}`)

getPageLabel

Secure
No

Returns the page label for the specified page.

getPageLabel(nPage)

nPage: [optional] The 0-based page number. The default is 0.

Returns the page label string.

example:

var label = this.getPageLabel(5)
console.println("Page 6 label: " + label) // Might print "vi" for roman numerals

getPageRotation

Secure
No

Returns the rotation of the specified page in degrees.

getPageRotation(nPage)

nPage: [optional] The 0-based page number. The default is 0.

Returns the rotation in degrees (0, 90, 180, or 270).

example:

var rotation = this.getPageRotation(0)
console.println("First page rotation: " + rotation)

getPrintParams

Secure
No

Returns a PrintParams object that can be used to control printing options.

getPrintParams()

Returns a PrintParams object.

example:

var pp = this.getPrintParams()
pp.firstPage = 0
pp.lastPage = 4
pp.interactive = pp.constants.interactionLevel.automatic
this.print(pp)

getTemplate

Secure
No

Returns a Template object with the specified name.

getTemplate(cName)

cName: Name of the template

Returns a Template object.

example:

var template = this.getTemplate("MyTemplate")

gotoNamedDest

Secure
No

Navigates to a named destination within the PDF file.

gotoNamedDest(cName)

cName: Name of the destination

example:

this.gotoNamedDest("Chapter2")

importAnFDF

Secure
No

Imports form field data and annotations from an FDF file.

importAnFDF(cPath)

cPath: [optional] The device-independent path of the FDF file to import. If not specified, the user will be prompted to select a file.

example:

this.importAnFDF("/c/data/form_data.fdf")

importDataObject

Secure
No

Imports a file as a data object (attachment) into the PDF.

importDataObject(cName, cDIPath, cCryptFilter)

cName: Name for the data object

cDIPath: [optional] The device-independent path of the file to import. If not specified, the user will be prompted to select a file. Requires elevated permissions when specified.

cCryptFilter: [optional] Not used by Revu

Returns true if the import was successful, false otherwise.

example:

// Prompt user to select a file
this.importDataObject("UserAttachment")

// Import specific file (requires elevated permissions)
this.importDataObject("Report", "/c/documents/report.xlsx")

importIcon

Secure
No

Imports an image file as an icon into the PDF.

importIcon(cName, cDIPath, nPage)

cName: Name for the icon

cDIPath: [optional] The device-independent path of the image file. If not specified, the user will be prompted to select a file. Requires elevated permissions when specified.

nPage: [optional] Page number if importing from a PDF file. Default is 0.

Returns:

  • 0 - Success
  • 1 - User cancelled
  • -1 - Could not open file
  • -2 - Invalid page number

example:

var result = this.importIcon("CompanyLogo")
if (result == 0) {
    console.println("Icon imported successfully")
}

insertPages

Secure
Yes

Inserts pages from another PDF file into the current document.

insertPages(nPage, cPath, nStart, nEnd)

nPage: [optional] 0-based page number after which to insert pages. Default is 0.

cPath: [optional] The device-independent path of the source PDF file. If not specified, the user will be prompted to select a file.

nStart: [optional] 0-based index of the first page to insert from the source. Default is 0.

nEnd: [optional] 0-based index of the last page to insert from the source. Default is nStart.

example:

// Insert all pages from another PDF after page 5
this.insertPages(5, "/c/documents/appendix.pdf")

// Insert pages 2-4 from another PDF after the first page
this.insertPages(1, "/c/documents/source.pdf", 2, 4)

mailDoc

Secure
No

Emails the PDF document as an attachment.

mailDoc(bUI, cTo, cCc, cBcc, cSubject, cMsg)

bUI: [optional] When true, the email client UI is shown. Default is true.

cTo: [optional] Semicolon-delimited list of recipients

cCc: [optional] Semicolon-delimited list of CC recipients

cBcc: [optional] Semicolon-delimited list of BCC recipients

cSubject: [optional] Email subject line

cMsg: [optional] Email body text

example:

this.mailDoc(true, "recipient@example.com", "", "", "PDF Document", "Please review the attached document.")

mailForm

Secure
No

Emails the form data as an FDF attachment.

mailForm(bUI, cTo, cCc, cBcc, cSubject, cMsg)

bUI: [optional] When true, the email client UI is shown. Default is true.

cTo: [optional] Semicolon-delimited list of recipients

cCc: [optional] Semicolon-delimited list of CC recipients

cBcc: [optional] Semicolon-delimited list of BCC recipients

cSubject: [optional] Email subject line

cMsg: [optional] Email body text

example:

this.mailForm(true, "forms@example.com", "", "", "Form Submission", "Form data attached.")

movePage

Secure
No

Moves a page to a new position within the document.

movePage(nPage, nAfter)

nPage: [optional] 0-based index of the page to move. Default is 0.

nAfter: [optional] 0-based index of the page after which to place the moved page. Use -1 to move to the beginning. Default is 0.

example:

// Move page 5 to the beginning
this.movePage(5, -1)

// Move page 2 after page 10
this.movePage(2, 10)

newPage

Secure
Yes

Inserts a new blank page into the document.

newPage(nPage, nWidth, nHeight)

nPage: [optional] 0-based index where the new page will be inserted. Default is 0.

nWidth: [optional] Width of the new page in points. Default is 612 (8.5 inches).

nHeight: [optional] Height of the new page in points. Default is 792 (11 inches).

example:

// Add a new letter-sized page at the beginning
this.newPage(0)

// Add a new A4 page (595 x 842 points) after page 3
this.newPage(3, 595, 842)

openDataObject

Secure
No

Opens an embedded PDF data object as a new document.

openDataObject(cName)

cName: Name of the data object to open

Returns a Doc object if the data object is a PDF, null otherwise.

example:

var attachedDoc = this.openDataObject("embedded.pdf")
if (attachedDoc) {
    console.println("Opened: " + attachedDoc.documentFileName)
}

print

Secure
No

Prints the document or specified pages.

print(bUI, nStart, nEnd, bSilent, bShrinkToFit, bPrintAsImage, bReverse, bAnnotations, printParams)

bUI: [optional] When false, prints without showing the print dialog. Requires elevated permissions. Default is true.

nStart: [optional] 0-based index of the first page to print. Default is 0.

nEnd: [optional] 0-based index of the last page to print. Default is last page.

bSilent: [optional] When true, suppresses the cancel dialog during printing. Default is false.

bShrinkToFit: [optional] When true, shrinks pages to fit the paper size. Default is false.

bPrintAsImage: [optional] When true, prints pages as images. Default is false.

bReverse: [optional] When true, prints pages in reverse order. Default is false.

bAnnotations: [optional] When true, prints annotations. Default is true.

printParams: [optional] A PrintParams object with print settings. When specified, other parameters are ignored.

example:

// Print with dialog
this.print()

// Print pages 1-3 silently (requires privileges)
this.print(false, 0, 2, true)

// Print using PrintParams object
var pp = this.getPrintParams()
pp.firstPage = 0
pp.lastPage = 4
this.print(pp)

removeDataObject

Secure
No

Removes an embedded data object from the PDF.

removeDataObject(cName)

cName: Name of the data object to remove

example:

this.removeDataObject("oldAttachment.xlsx")

removeField

Secure
No

Removes a form field from the PDF.

removeField(cName)

cName: Name of the field to remove

example:

this.removeField("obsoleteField")

removeIcon

Secure
No

Removes an icon from the PDF.

removeIcon(cName)

cName: Name of the icon to remove

example:

this.removeIcon("oldLogo")

resetForm

Secure
No

Resets form fields to their default values.

resetForm(aFields)

aFields: [optional] Array of field names to reset. If not specified, all fields are reset.

example:

// Reset all fields
this.resetForm()

// Reset specific fields
this.resetForm(["name", "email", "phone"])

setDataObjectContents

Secure
No

Updates the contents of an existing data object.

setDataObjectContents(cName, oStream, cCryptFilter)

cName: Name of the data object to update

oStream: A ReadStream object containing the new contents

cCryptFilter: [optional] Not used by Revu

example:

var stream = util.streamFromString("New file contents", "utf-8")
this.setDataObjectContents("data.txt", stream)

setPageBoxes

Secure
No

Sets the dimensions of a page box for specified pages.

setPageBoxes(cBox, nStart, nEnd, rBox)

cBox: [optional] Type of page box to set. Default is "Crop". Valid values are:

  • "Art"
  • "Bleed"
  • "Crop"
  • "Media"
  • "Trim"

nStart: [optional] 0-based index of the first page. Default is 0.

nEnd: [optional] 0-based index of the last page. Default is nStart.

rBox: [optional] Array of 4 numbers [left, top, right, bottom] defining the rectangle.

example:

// Set crop box for page 1
this.setPageBoxes("Crop", 0, 0, [72, 72, 540, 720])

// Set media box for all pages
this.setPageBoxes("Media", 0, this.numPages - 1, [0, 0, 612, 792])

setPageLabels

Secure
No

Sets page labels for specified pages.

setPageLabels(nPage, aLabel)

nPage: [optional] 0-based page number where labeling begins. Default is 0.

aLabel: [optional] Array with label settings:

  • [0] - Style: "", "D" (decimal), "r" (lowercase roman), "R" (uppercase roman), "a" (lowercase letters), "A" (uppercase letters)
  • [1] - Prefix string
  • [2] - Starting number

example:

// Set pages to use roman numerals starting with "i"
this.setPageLabels(0, ["r", "", 1])

// Set pages to use "Chapter A-" prefix with uppercase letters
this.setPageLabels(10, ["A", "Chapter ", 1])

// Remove page labels
this.setPageLabels(0)

setPageRotations

Secure
No

Sets the rotation for specified pages.

setPageRotations(nStart, nEnd, nRotate)

nStart: [optional] 0-based index of the first page. If not specified, applies to all pages.

nEnd: [optional] 0-based index of the last page. Default is nStart.

nRotate: [optional] Rotation in degrees (0, 90, 180, or 270). Default is 0.

example:

// Rotate page 1 by 90 degrees
this.setPageRotations(0, 0, 90)

// Rotate pages 5-10 by 180 degrees
this.setPageRotations(5, 10, 180)

// Reset all pages to 0 rotation
this.setPageRotations(0, this.numPages - 1, 0)

spawnPageFromTemplate

Secure
No

Creates a new page from a template.

spawnPageFromTemplate(cTemplate, nPage, bRename, bOverlay, oXObject)

cTemplate: Name of the template to spawn

nPage: [optional] 0-based page number where the template will be spawned. Default is 0.

bRename: [optional] When true, renames fields to avoid conflicts. Default is true.

bOverlay: [optional] When true, overlays the template on an existing page. When false, inserts as a new page. Default is true.

oXObject: [optional] Object with form field data to populate the spawned template

example:

// Spawn template as overlay on page 5
this.spawnPageFromTemplate("InvoiceTemplate", 5, true, true)

// Spawn template as new page with data
var data = {
    "invoice_number": "12345",
    "date": "2024-01-15",
    "amount": "$1,234.56"
}
this.spawnPageFromTemplate("InvoiceTemplate", 3, true, false, data)

submitForm

Secure
No

Submits form data to a specified URL.

submitForm(cURL, bFDF, bEmpty, aFields, bGet, bAnnotations, bXML, bIncrChanges, bPDF, bCanonical, bExclNonUserAnnots, bExclFKey, cPassword, bEmbedForm, oJavaScript, cSubmitAs, bInclNMKey, aPackets, cCharset, oXML, cPermID, cInstID, cUsageRights)

cURL: URL to submit the form to

bFDF: [optional] When true, submit as FDF. Default is true.

bEmpty: [optional] When true, include fields with no value. Default is false.

aFields: [optional] Array of field names to submit. If not specified, all fields are submitted.

bGet: [optional] When true, use HTTP GET. When false, use POST. Default is false.

bAnnotations: [optional] When true, include annotations. Default is false.

bXML: [optional] When true, submit as XML. Default is false.

bIncrChanges: [optional] Not supported by Revu

bPDF: [optional] When true, submit the entire PDF. Default is false.

bCanonical: [optional] When true, include a canonical format. Default is false.

bExclNonUserAnnots: [optional] When true, exclude non-user annotations. Default is false.

bExclFKey: [optional] When true, exclude the F key. Default is false.

cPassword: [optional] Not supported by Revu

bEmbedForm: [optional] When true, embed the form in the submitted data. Default is false.

oJavaScript: [optional] Not supported by Revu

cSubmitAs: [optional] Format for submission: "FDF", "HTML", or "PDF". Default is "FDF".

bInclNMKey: [optional] When true, include the NM key. Default is false.

aPackets: [optional] Not supported by Revu

cCharset: [optional] Character set for submission

oXML: [optional] Not supported by Revu

cPermID: [optional] Not supported by Revu

cInstID: [optional] Not supported by Revu

cUsageRights: [optional] Not supported by Revu

example:

// Submit all form fields as FDF
this.submitForm("https://example.com/submit")

// Submit specific fields as HTML POST
this.submitForm("https://example.com/submit", false, false, ["name", "email"], false, false, false, false, false, false, false, false, null, false, null, "HTML")

syncAnnotScan

Secure
No

Ensures that all annotations have been scanned. Exists for compatibility reasons.

syncAnnotScan()


event

The event object provides access to information about the current JavaScript event being processed. Unlike other JavaScript objects in Revu, the event object is not directly accessible through this or other means. Instead, it is automatically available in the scope of event handler scripts when they are executed.

Events in Revu are triggered by various user interactions and document actions. When an event occurs, the associated JavaScript code is executed with an event object that contains contextual information about what triggered the event. The properties available on the event object vary depending on the type of event being processed.

The event object is read-only for most properties, but certain properties like change, rc, selEnd, selStart, and value can be modified to affect the outcome of the event. For example, setting event.rc = false in a validation script will prevent the action from completing.

Event Types

Revu supports various event types that can trigger JavaScript execution:

  • App Events: Application initialization
  • Doc Events: Document open, close, print, and save operations
  • Field Events: Form field interactions including focus, blur, calculate, format, keystroke, validate, and mouse events
  • Page Events: Page open and close
  • Bookmark Events: Bookmark mouse interactions
  • Console Events: Console command execution

example:

// In a field validation script
if (event.value < 0) {
    app.alert("Value must be positive");
    event.rc = false; // Prevent the negative value from being accepted
}

properties

change

SecureTypeAccess
NostringR/W

The text being entered or pasted into a field during a keystroke event. This property is only present for Field_Keystroke events when text is being modified.

When processing keystroke events, you can modify this property to change what text will be inserted. Setting event.change = "" will prevent the character from being entered.

example:

// In a field keystroke script - convert to uppercase
event.change = event.change.toUpperCase();

// Prevent non-numeric characters
if (!/^\d*$/.test(event.change)) {
    event.change = "";
}

changeEx

SecureTypeAccess
NostringR

Contains the export value of the item that was selected in a combobox or listbox during a keystroke event. This is particularly useful when the display value and export value of list items differ.

For regular text input, this property contains the same value as change.

example:

// In a combobox keystroke script
console.println("Display value: " + event.change);
console.println("Export value: " + event.changeEx);

commitKey

SecureTypeAccess
NonumberR

Indicates how the user committed the field value during a keystroke event when willCommit is true. This helps determine what action caused the field to lose focus.

Valid values:

  • 0: Value was not committed (willCommit is false)
  • 1: User pressed Enter key
  • 2: User pressed Tab key to move to next field
  • 3: User clicked outside the field or otherwise caused it to lose focus

example:

// In a field keystroke script
if (event.willCommit) {
    switch(event.commitKey) {
        case 1:
            console.println("User pressed Enter");
            break;
        case 2:
            console.println("User pressed Tab");
            break;
        case 3:
            console.println("Field lost focus");
            break;
    }
}

fieldFull

SecureTypeAccess
NobooleanR

Indicates whether the field is full during a keystroke event. This is true when the user attempts to enter more characters than the field's character limit allows.

This property is useful for providing feedback when users reach the maximum character limit of a field.

example:

// In a field keystroke script
if (event.fieldFull) {
    app.beep(0);
    console.println("Field has reached maximum character limit");
}

keyDown

SecureTypeAccess
NobooleanR

For mouse events, indicates whether a keyboard key was being held down when the mouse event occurred. This is always false for non-mouse events.


modifier

SecureTypeAccess
NobooleanR

Indicates whether the CTRL key was held down during a mouse event. This property is only present for mouse events.

example:

// In a field mouse up script
if (event.modifier) {
    console.println("CTRL was held during click");
}

name

SecureTypeAccess
NostringR

The name of the current event. This indicates what specific action triggered the event within its type category.

Possible values include:

  • "Init" - App initialization
  • "Exec" - Execution events (Batch, Console, External, Menu, Doc)
  • "Open" - Opening events (Doc, Page, Screen)
  • "Close" - Closing events (Page, Screen)
  • "Mouse Up" - Mouse up events (Bookmark, Field, Screen, Link)
  • "Mouse Down" - Mouse down events (Field, Screen)
  • "Mouse Enter" - Mouse enter events (Field, Screen)
  • "Mouse Exit" - Mouse exit events (Field, Screen)
  • "Calculate" - Field calculation
  • "Validate" - Field validation
  • "Format" - Field formatting
  • "Keystroke" - Field keystroke
  • "Focus" - Focus events (Field, Screen)
  • "Blur" - Blur events (Field, Screen)
  • "WillClose" - Document will close
  • "WillPrint" - Document will print
  • "WillSave" - Document will save
  • "DidPrint" - Document did print
  • "DidSave" - Document did save

example:

console.println("Event name: " + event.name);
console.println("Event type: " + event.type);

rc

SecureTypeAccess
NobooleanR/W

Return code that determines whether the event should proceed. Setting this to false cancels the event and prevents the associated action from completing.

This is one of the most important properties for controlling event behavior. It defaults to true, meaning the event will proceed normally. Setting it to false in validation, keystroke, or other "Will" events prevents the action.

example:

// In a field validation script
if (event.value < 0 || event.value > 100) {
    app.alert("Value must be between 0 and 100");
    event.rc = false; // Prevent invalid value
}

// In a Doc WillSave script
if (!this.getField("RequiredField").value) {
    app.alert("Required field is empty");
    event.rc = false; // Prevent save
}

richChange

SecureTypeAccess
NoarrayR/W

Array of Span objects representing rich text formatting changes during a keystroke event in a rich text field. Each Span object contains formatting information for a portion of text.

This property is only present when editing rich text fields and allows you to modify the formatting of the text being entered.


richChangeEx

SecureTypeAccess
NoarrayR

Array of Span objects representing the rich text formatting of text that was deleted or replaced during a keystroke event in a rich text field.


richValue

SecureTypeAccess
NoarrayR/W

Array of Span objects representing the complete rich text value of a field. This property is available during format and keystroke events for rich text fields.


selEnd

SecureTypeAccess
NonumberR/W

The ending character position of the current text selection in a field during keystroke events. This is the character position where the selection ends or where the cursor is positioned if there's no selection.

You can modify this value to change the selection programmatically.

example:

// In a field keystroke script
console.println("Selection: " + event.selStart + " to " + event.selEnd);

// Select all text after validation
if (event.willCommit && !isValid(event.value)) {
    event.selStart = 0;
    event.selEnd = event.value.length;
}

selStart

SecureTypeAccess
NonumberR/W

The starting character position of the current text selection in a field during keystroke events. If there's no selection (just a cursor position), this equals selEnd.

example:

// Check if text is selected
if (event.selStart != event.selEnd) {
    var selectedText = event.value.substring(event.selStart, event.selEnd);
    console.println("Selected text: " + selectedText);
}

shift

SecureTypeAccess
NobooleanR

Indicates whether the Shift key was held down during a mouse event. This property is only present for mouse events.

example:

// In a field mouse up script
if (event.shift) {
    console.println("Shift was held during click");
    // Perform special action for Shift+Click
}

source

SecureTypeAccess
NoobjectR

The object that triggered the event. For field events, this is typically the Field object. For document events, this is the Doc object. For bookmark events, this is the Bookmark object.

The source represents where the event originated from, while target represents what object the event is acting upon.

example:

// In a field calculate script
console.println("Source field: " + event.source.name);
console.println("Source value: " + event.source.value);

target

SecureTypeAccess
NoobjectR

The target object of the event. For field events, this is the Field object being acted upon. For document events, this is the Doc object.

In many cases, source and target are the same object, but they can differ in calculation scripts where one field's change (source) triggers another field's calculation (target).

example:

// In a field calculate script
if (event.source != event.target) {
    console.println("Calculation triggered by: " + event.source.name);
    console.println("Calculating for: " + event.target.name);
}

targetName

SecureTypeAccess
NostringR

The name of the target object. For field events, this is the field name. This provides a convenient way to get the target's name without accessing the target object directly.

example:

// In a field script
console.println("Event occurring on field: " + event.targetName);

// Perform different actions based on field name
switch(event.targetName) {
    case "Total":
        // Special handling for Total field
        break;
    case "Subtotal":
        // Special handling for Subtotal field
        break;
}

type

SecureTypeAccess
NostringR

The type category of the event, indicating what kind of object or action triggered it.

Possible values:

  • "App" - Application events
  • "Bookmark" - Bookmark events
  • "Console" - Console events
  • "Doc" - Document events
  • "External" - External events
  • "Field" - Form field events
  • "Link" - Link events
  • "Menu" - Menu events
  • "Page" - Page events

example:

// Determine what kind of event is occurring
console.println("Event type: " + event.type);
console.println("Event name: " + event.name);

if (event.type == "Field") {
    console.println("This is a field event");
}

value

SecureTypeAccess
NostringR/W

The value associated with the event. The meaning depends on the event type:

  • For field validation and calculation events: The proposed new value of the field
  • For field format events: The value to be formatted for display
  • For field keystroke events when willCommit is true: The value about to be committed

You can modify this property in format events to change how the value is displayed, or in validation events to modify the value before it's committed.

example:

// In a field validation script
if (event.value != "") {
    // Ensure value is within range
    if (event.value < 0) {
        event.value = 0;
    } else if (event.value > 100) {
        event.value = 100;
    }
}

// In a field format script
if (event.value != "") {
    // Format as currency
    event.value = "$" + parseFloat(event.value).toFixed(2);
}

willCommit

SecureTypeAccess
NobooleanR

For keystroke events, indicates whether the field value is about to be committed (true) or whether the user is still typing (false).

When true, the keystroke event represents the final value being committed to the field. When false, the event represents individual character input as the user types.

This property is essential for distinguishing between character-by-character validation and final value validation.

example:

// In a field keystroke script
if (event.willCommit) {
    // Validate complete value
    if (event.value == "") {
        app.alert("Field cannot be empty");
        event.rc = false;
    }
} else {
    // Validate individual keystrokes
    // Allow only numeric input
    if (!/^\d*$/.test(event.change)) {
        event.rc = false;
    }
}

Field

Field object represents a form field in a PDF document. It provides access to form field properties and methods for manipulating field appearance and behavior. Field objects are typically accessed through Doc.getField or other field-related methods.

properties

alignment

SecureTypeAccess
NostringR/W

The text alignment for text fields. Only applicable to text fields.

Valid values:

  • "left"
  • "center"
  • "right"

example:

var field = this.getField("myTextField")
field.alignment = "center"

borderStyle

SecureTypeAccess
NostringR/W

The border style of the field.

Valid values:

  • "solid"
  • "beveled"
  • "dashed"
  • "inset"
  • "underline"

example:

var field = this.getField("myField")
field.borderStyle = "beveled"

buttonAlignX

SecureTypeAccess
NonumberR/W

The horizontal alignment of the icon on a button field. Value is a percentage from 0 to 100. Only applicable to pushbutton fields.

0 represents left alignment, 50 represents center, and 100 represents right alignment.

example:

var button = this.getField("myButton")
button.buttonAlignX = 50 // Center the icon horizontally

buttonAlignY

SecureTypeAccess
NonumberR/W

The vertical alignment of the icon on a button field. Value is a percentage from 0 to 100. Only applicable to pushbutton fields.

0 represents bottom alignment, 50 represents center, and 100 represents top alignment.

example:

var button = this.getField("myButton")
button.buttonAlignY = 50 // Center the icon vertically

buttonFitBounds

SecureTypeAccess
NobooleanR/W

When true, the button icon ignores the border width when sizing. Only applicable to pushbutton fields. Cannot be set to true if the field has a visible border.

example:

var button = this.getField("myButton")
button.buttonFitBounds = true

buttonPosition

SecureTypeAccess
NonumberR/W

Controls the layout mode for the button caption and icon. Only applicable to pushbutton fields.

Valid values:

  • 0 - Caption only
  • 1 - Icon only
  • 2 - Caption below icon
  • 3 - Caption above icon
  • 4 - Caption to the right of icon
  • 5 - Caption to the left of icon
  • 6 - Caption overlaid on icon

example:

var button = this.getField("myButton")
button.buttonPosition = 2 // Caption below icon

buttonScaleHow

SecureTypeAccess
NonumberR/W

Controls how the button icon is scaled. Only applicable to pushbutton fields.

Valid values:

  • 0 - Always scale
  • 1 - Scale when icon is bigger than bounds
  • 2 - Scale when icon is smaller than bounds
  • 3 - Never scale

example:

var button = this.getField("myButton")
button.buttonScaleHow = 0 // Always scale

buttonScaleWhen

SecureTypeAccess
NonumberR/W

Controls when the button icon scales. Only applicable to pushbutton fields.

Valid values:

  • 0 - Always
  • 1 - Never
  • 2 - When icon is too big
  • 3 - When icon is too small

example:

var button = this.getField("myButton")
button.buttonScaleWhen = 0 // Always

calcOrderIndex

SecureTypeAccess
NonumberR/W

The calculation order index for this field. Fields with lower indices are calculated first. When setting, if the index is greater than the number of fields with calculations it will be set to the last position.

example:

var field = this.getField("totalField")
field.calcOrderIndex = 0 // Calculate this field first

charLimit

SecureTypeAccess
NonumberR/W

The maximum number of characters allowed in a text field. A value of 0 means no limit. Only applicable to text fields.

example:

var field = this.getField("zipCode")
field.charLimit = 5

comb

SecureTypeAccess
NobooleanR/W

When true, the text field is divided into equally spaced character positions. Only applicable to text fields. Cannot be true if multiline, password, or fileSelect is true.

example:

var field = this.getField("serialNumber")
field.comb = true
field.charLimit = 10 // Divide into 10 character boxes

commitOnSelChange

SecureTypeAccess
NobooleanR/W

When true, the field value is committed immediately when the selection changes. Only applicable to list box and combo box fields.

example:

var combo = this.getField("myComboBox")
combo.commitOnSelChange = true

currentValueIndices

SecureTypeAccess
Nonumber/arrayR/W

The index or indices of the currently selected items in a choice field. For single-selection fields, this is a number. For multiple-selection list boxes, this is an array of numbers. Returns -1 if nothing is selected.

example:

var list = this.getField("myListBox")
list.currentValueIndices = 2 // Select the third item

// For multiple selection
list.currentValueIndices = [0, 2, 4] // Select items 1, 3, and 5

defaultStyle

SecureTypeAccess
NoobjectR/W

The default style for rich text fields. Only applicable to rich text fields. Returns a Span object containing style information.

example:

var field = this.getField("richTextField")
var style = field.defaultStyle
console.println(style.fontFamily)

defaultValue

SecureTypeAccess
NostringR/W

The default value of the field. This is the value the field reverts to when reset.

example:

var field = this.getField("myField")
field.defaultValue = "Enter text here"

delay

SecureTypeAccess
NobooleanR/W

Exists for compatibility reasons. Always returns false. Setting has no effect.


display

SecureTypeAccess
NonumberR/W

Controls the visibility and printing behavior of the field.

Valid values:

  • 0 - Visible
  • 1 - Hidden
  • 2 - Visible but doesn't print
  • 3 - Hidden but prints

example:

var field = this.getField("myField")
field.display = 2 // Visible on screen but won't print

doc

SecureTypeAccess
NoobjectR

The Doc object that contains this field.

example:

var field = this.getField("myField")
var doc = field.doc
console.println(doc.numPages)

doNotScroll

SecureTypeAccess
NobooleanR/W

When true, the text field does not scroll to accommodate more text than fits in the field bounds. Only applicable to text fields.

example:

var field = this.getField("myTextField")
field.doNotScroll = true

doNotSpellCheck

SecureTypeAccess
NobooleanR/W

When true, spell checking is disabled for the text field. Only applicable to text fields.

example:

var field = this.getField("myTextField")
field.doNotSpellCheck = true

editable

SecureTypeAccess
NobooleanR/W

When true, the combo box allows custom text entry. Only applicable to combo box fields.

example:

var combo = this.getField("myComboBox")
combo.editable = true

exportValues

SecureTypeAccess
NoarrayR/W

Array of export values for the widgets of a checkbox or radio button field. Only applicable to checkbox and radio button fields.

example:

var check = this.getField("myCheckBox")
check.exportValues = ["Yes", "No"]

fileSelect

SecureTypeAccess
YesbooleanR/W

When true, the text field is used for file selection. Only applicable to text fields. Requires elevated privileges to set.

example:

var field = this.getField("filePathField")
field.fileSelect = true

fillColor

SecureTypeAccess
NoobjectR/W

The background color of the field. Value is a color array in the same format as the color object.

example:

var field = this.getField("myField")
field.fillColor = color.yellow

hidden

SecureTypeAccess
NobooleanR/W

When true, the field is hidden. Equivalent to setting display to 1.

example:

var field = this.getField("myField")
field.hidden = true

highlight

SecureTypeAccess
NostringR/W

The highlighting mode for pushbutton fields. Only applicable to pushbutton fields.

Valid values:

  • "none"
  • "invert"
  • "push"
  • "outline"

example:

var button = this.getField("myButton")
button.highlight = "push"

lineWidth

SecureTypeAccess
NonumberR/W

The border width of the field in points.

example:

var field = this.getField("myField")
field.lineWidth = 2

multiline

SecureTypeAccess
NobooleanR/W

When true, the text field can contain multiple lines of text. Only applicable to text fields.

example:

var field = this.getField("commentsField")
field.multiline = true

multipleSelection

SecureTypeAccess
NobooleanR/W

When true, multiple items can be selected in a list box. Only applicable to list box fields.

example:

var list = this.getField("myListBox")
list.multipleSelection = true

name

SecureTypeAccess
NostringR

The fully qualified name of the field.

example:

var field = this.getField("parent.child")
console.println(field.name) // "parent.child"

numItems

SecureTypeAccess
NonumberR

The number of items in a choice field (list box or combo box). Only applicable to choice fields.

example:

var list = this.getField("myListBox")
console.println("List has " + list.numItems + " items")

page

SecureTypeAccess
Nonumber/arrayR

The 0-based page number(s) where the field appears. Returns a single number if the field appears on one page, or an array of numbers if it appears on multiple pages.

example:

var field = this.getField("myField")
console.println("Field is on page " + field.page)

password

SecureTypeAccess
NobooleanR/W

When true, the text field displays asterisks or bullets instead of the actual characters. Only applicable to text fields.

example:

var field = this.getField("passwordField")
field.password = true

SecureTypeAccess
NobooleanR/W

When true, the field will print when the document is printed.

example:

var field = this.getField("myField")
field.print = false // Don't print this field

radiosInUnison

SecureTypeAccess
NobooleanR/W

When true, radio buttons with the same export value in a radio button group will toggle in unison. Only applicable to radio button fields.

example:

var radio = this.getField("myRadioGroup")
radio.radiosInUnison = true

readonly

SecureTypeAccess
NobooleanR/W

When true, the field cannot be changed by the user.

example:

var field = this.getField("calculatedField")
field.readonly = true

rect

SecureTypeAccess
NoarrayR/W

The rectangle that defines the field's position and size on the page. Array is in the form [left, top, right, bottom] in points.

example:

var field = this.getField("myField")
field.rect = [100, 100, 200, 120] // Position at (100, 100) with width 100 and height 20

required

SecureTypeAccess
NobooleanR/W

When true, the field must have a value when the form is submitted.

example:

var field = this.getField("emailField")
field.required = true

richText

SecureTypeAccess
NobooleanR/W

When true, the text field supports rich text formatting. Only applicable to text fields.

example:

var field = this.getField("myTextField")
field.richText = true

richValue

SecureTypeAccess
NoarrayR/W

The rich text value of the field as an array of Span objects. Only applicable to rich text fields.

example:

var field = this.getField("richTextField")
var spans = field.richValue
// spans is an array of Span objects with formatting

rotation

SecureTypeAccess
NonumberR/W

The rotation of the field in degrees. Valid values are 0, 90, 180, or 270.

example:

var field = this.getField("myField")
field.rotation = 90 // Rotate 90 degrees clockwise

strokeColor

SecureTypeAccess
NoobjectR/W

The border color of the field. Value is a color array in the same format as the color object.

example:

var field = this.getField("myField")
field.strokeColor = color.red

style

SecureTypeAccess
NostringR/W

The style of checkmark for checkbox and radio button fields. Only applicable to checkbox and radio button fields.

Valid values:

  • "check"
  • "cross"
  • "diamond"
  • "circle"
  • "star"
  • "square"

example:

var check = this.getField("myCheckBox")
check.style = "diamond"

submitName

SecureTypeAccess
NostringR/W

The name used when submitting the field data. If not set, the field name is used.

example:

var field = this.getField("myField")
field.submitName = "custom_field_name"

textColor

SecureTypeAccess
NoobjectR/W

The text color of the field. Value is a color array in the same format as the color object.

example:

var field = this.getField("myField")
field.textColor = color.blue

textFont

SecureTypeAccess
NostringR/W

The font used for text in the field. Valid values are the standard 14 PDF fonts.

Valid values:

  • "Times-Roman"
  • "Times-Bold"
  • "Times-Italic"
  • "Times-BoldItalic"
  • "Helvetica"
  • "Helvetica-Bold"
  • "Helvetica-Oblique"
  • "Helvetica-BoldOblique"
  • "Courier"
  • "Courier-Bold"
  • "Courier-Oblique"
  • "Courier-BoldOblique"
  • "Symbol"
  • "ZapfDingbats"

example:

var field = this.getField("myField")
field.textFont = "Helvetica-Bold"

textSize

SecureTypeAccess
NonumberR/W

The text size in points. A value of 0 means auto-size.

example:

var field = this.getField("myField")
field.textSize = 12

type

SecureTypeAccess
NostringR

The type of the field.

Possible values:

  • "button"
  • "checkbox"
  • "radiobutton"
  • "combobox"
  • "listbox"
  • "text"
  • "signature"

example:

var field = this.getField("myField")
if (field.type == "text") {
    field.multiline = true
}

userName

SecureTypeAccess
NostringR/W

The user-friendly name of the field, used for tooltips and error messages.

example:

var field = this.getField("email")
field.userName = "Email Address"

value

SecureTypeAccess
NovariousR/W

The value of the field. The type depends on the field type:

  • Text fields: string or number
  • Checkboxes/Radio buttons: string export value
  • List boxes (single selection): string
  • List boxes (multiple selection): array of strings
  • Combo boxes: string

example:

var textField = this.getField("myTextField")
textField.value = "Hello World"

var checkBox = this.getField("myCheckBox")
checkBox.value = "Yes"

var listBox = this.getField("myListBox")
listBox.value = ["Option1", "Option2"] // For multiple selection

valueAsString

SecureTypeAccess
NostringR

The value of the field as a string, regardless of the actual value type.

example:

var field = this.getField("numberField")
field.value = 123.45
console.println(field.valueAsString) // "123.45"

methods

browseForFileToSubmit

Secure
No

Opens a file browser dialog for selecting a file path. Only works with text fields that have fileSelect set to true.

browseForFileToSubmit()

example:

var field = this.getField("fileField")
field.fileSelect = true
field.browseForFileToSubmit() // Opens file browser

buttonGetCaption

Secure
No

Returns the caption text for a button field.

buttonGetCaption(nFace)

nFace: [optional] The button face to get the caption from:

  • 0 - Normal (default)
  • 1 - Down
  • 2 - Rollover

Returns the caption string.

example:

var button = this.getField("myButton")
var caption = button.buttonGetCaption(0)
console.println("Button caption: " + caption)

buttonGetIcon

Secure
No

Returns the icon for a button field.

buttonGetIcon(nFace)

nFace: [optional] The button face to get the icon from:

  • 0 - Normal (default)
  • 1 - Down
  • 2 - Rollover

Returns an Icon object or null if no icon is set.

example:

var button = this.getField("myButton")
var icon = button.buttonGetIcon(0)
if (icon != null) {
    // Use the icon elsewhere
    var otherButton = this.getField("otherButton")
    otherButton.buttonSetIcon(icon)
}

buttonImportIcon

Secure
Yes

Imports an image file as the button icon. Requires elevated privileges if a path is specified.

buttonImportIcon(cPath, nPage)

cPath: [optional] The device-independent path to the image file. If not specified, a file dialog is shown.

nPage: [optional] If importing from a PDF, the 0-based page number. Default is 0.

Returns:

  • 0 - Success
  • 1 - User cancelled
  • -1 - Could not open file
  • -2 - Invalid page number

example:

var button = this.getField("myButton")
var result = button.buttonImportIcon() // Show file dialog
if (result == 0) {
    console.println("Icon imported successfully")
}

// With privileges
var result = button.buttonImportIcon("/c/images/icon.png")

buttonSetCaption

Secure
No

Sets the caption text for a button field.

buttonSetCaption(cCaption, nFace)

cCaption: The caption text to set

nFace: [optional] The button face to set the caption for:

  • 0 - Normal (default)
  • 1 - Down
  • 2 - Rollover

example:

var button = this.getField("myButton")
button.buttonSetCaption("Click Me!")
button.buttonSetCaption("Pressed", 1) // Down state

buttonSetIcon

Secure
No

Sets the icon for a button field.

buttonSetIcon(oIcon, nFace)

oIcon: An Icon object to set as the button icon

nFace: [optional] The button face to set the icon for:

  • 0 - Normal (default)
  • 1 - Down
  • 2 - Rollover

example:

var button1 = this.getField("button1")
var icon = button1.buttonGetIcon()

var button2 = this.getField("button2")
button2.buttonSetIcon(icon) // Copy icon to another button

checkThisBox

Secure
No

Checks or unchecks a specific widget in a checkbox or radio button field. Only applicable to checkbox and radio button fields.

checkThisBox(nWidget, bCheckIt)

nWidget: The 0-based index of the widget to check

bCheckIt: [optional] When true, checks the box. When false, unchecks it. Default is true. For radio buttons, cannot be false.

example:

var check = this.getField("myCheckBox")
check.checkThisBox(0, true) // Check the first widget

var radio = this.getField("myRadioGroup")
radio.checkThisBox(2, true) // Select the third radio button

clearItems

Secure
No

Removes all items from a choice field (combo box or list box).

clearItems()

example:

var list = this.getField("myListBox")
list.clearItems() // Remove all items

defaultIsChecked

Secure
No

Sets whether a checkbox or radio button widget is checked by default. Only applicable to checkbox and radio button fields.

defaultIsChecked(nWidget, bIsDefaultChecked)

nWidget: The 0-based index of the widget

bIsDefaultChecked: [optional] When true, the widget is checked by default. Default is true.

example:

var check = this.getField("myCheckBox")
check.defaultIsChecked(0, true) // First widget checked by default

deleteItemAt

Secure
No

Deletes an item from a choice field at the specified index.

deleteItemAt(nIdx)

nIdx: [optional] The 0-based index of the item to delete. If -1 or not specified, deletes the currently selected item.

example:

var list = this.getField("myListBox")
list.deleteItemAt(2) // Delete the third item
list.deleteItemAt() // Delete the currently selected item

getArray

Secure
No

Returns an array of Field objects for all terminal children of this field. Terminal children are the leaf nodes in the field hierarchy.

getArray()

Returns an array of Field objects.

example:

var parentField = this.getField("parent")
var children = parentField.getArray()
for (var i = 0; i < children.length; i++) {
    console.println(children[i].name)
}

getItemAt

Secure
No

Returns the item at the specified index in a choice field.

getItemAt(nIdx, bExportValue)

nIdx: The 0-based index of the item

bExportValue: [optional] When true, returns the export value. When false, returns the display value. Default is true.

Returns the item string.

example:

var list = this.getField("myListBox")
var exportVal = list.getItemAt(0, true) // Get export value
var displayVal = list.getItemAt(0, false) // Get display value

getLock

Secure
No

Returns the lock settings for a signature field. Only applicable to signature fields.

getLock()

Returns a Lock object with properties:

  • action - The lock action ("All", "Include", or "Exclude")
  • fields - Array of field names to lock

Returns null if no lock is set.

example:

var sig = this.getField("signatureField")
var lock = sig.getLock()
if (lock != null) {
    console.println("Lock action: " + lock.action)
}

insertItemAt

Secure
No

Inserts an item into a choice field at the specified position.

insertItemAt(cName, cExport, nIdx)

cName: The display name for the item

cExport: [optional] The export value for the item. If not specified, uses cName.

nIdx: [optional] The 0-based index where to insert. Default is 0. If negative, appends to the end.

example:

var list = this.getField("myListBox")
list.insertItemAt("New Item", "new_value", 0) // Insert at beginning
list.insertItemAt("Another Item") // Insert at beginning with same export value

isBoxChecked

Secure
No

Returns whether a specific widget in a checkbox or radio button field is checked.

isBoxChecked(nWidget)

nWidget: The 0-based index of the widget to check

Returns true if checked, false otherwise.

example:

var check = this.getField("myCheckBox")
if (check.isBoxChecked(0)) {
    console.println("First checkbox is checked")
}

isDefaultChecked

Secure
No

Returns whether a specific widget in a checkbox or radio button field is checked by default.

isDefaultChecked(nWidget)

nWidget: The 0-based index of the widget to check

Returns true if checked by default, false otherwise.

example:

var check = this.getField("myCheckBox")
if (check.isDefaultChecked(0)) {
    console.println("First checkbox is checked by default")
}

setAction

Secure
No

Sets a JavaScript action for a field trigger.

setAction(cTrigger, cScript)

cTrigger: The trigger name. Valid values:

  • "MouseUp"
  • "MouseDown"
  • "MouseEnter"
  • "MouseExit"
  • "OnFocus"
  • "OnBlur"
  • "Keystroke"
  • "Validate"
  • "Calculate"
  • "Format"

cScript: The JavaScript code to execute

example:

var field = this.getField("myField")
field.setAction("MouseUp", "app.alert('Field clicked!')")
field.setAction("Validate", "event.rc = event.value.length > 0")

setFocus

Secure
No

Sets the keyboard focus to this field.

setFocus()

example:

var field = this.getField("myField")
field.setFocus() // Move cursor to this field

setItems

Secure
No

Sets all items in a choice field, replacing any existing items.

setItems(oArray)

oArray: An array where each element is either:

  • A string (both display and export value will be the same)
  • A two-element array [display, export]

example:

var list = this.getField("myListBox")
// Simple items
list.setItems(["Option 1", "Option 2", "Option 3"])

// Items with different export values
list.setItems([
    ["Display 1", "value1"],
    ["Display 2", "value2"],
    ["Display 3", "value3"]
])

setLock

Secure
Yes

Sets the lock settings for a signature field. Only applicable to signature fields. Requires elevated privileges.

setLock(oLock)

oLock: A Lock object with properties:

  • action - "All", "Include", or "Exclude"
  • fields - Array of field names to lock (required for Include/Exclude)

Returns true if successful.

example:

var sig = this.getField("signatureField")
var lock = {
    action: "Include",
    fields: ["field1", "field2", "field3"]
}
sig.setLock(lock)

global

The global object provides access to persistent variables that can be shared across documents and Revu sessions. Variables stored on the global object persist for the current Revu session, and can optionally be made to persist across Revu restarts.

example:

// Store a value globally
global.userName = "John Smith"

// Access from another document
console.println(global.userName) // Outputs: John Smith

// Delete a global variable
delete global.userName

methods

setPersistent

Secure
No

Controls whether a global variable persists across Revu sessions.

setPersistent(cVariable, bPersist)

cVariable: Name of the global variable. The variable must already exist on the global object.

bPersist: When true, the variable persists across Revu sessions. When false, the variable only exists for the current session.

Throws an exception if the operation fails.

example:

global.companyName = "Acme Corp"
global.setPersistent("companyName", true) // Will persist after Revu restart

Icon

Icon object represents an icon stored at the document level in a PDF file. Icons can be used with button form fields to display custom images. Icons are accessed through the Doc.icons property or created using Doc.addIcon.

example:

// Get an existing icon from the document
var icon = this.getIcon("MyIcon")

// Apply the icon to a button field
var button = this.getField("MyButton")
button.buttonSetIcon(icon)

properties

name

SecureTypeAccess
NostringR

The name of the icon as stored in the PDF document.

example:

// List all icon names in the document
if (this.icons != null) {
    this.icons.forEach(icon => {
        console.println("Icon name: " + icon.name)
    })
}

methods

Icon objects in Revu do not expose any public methods. Icons are managed through the Doc object methods such as addIcon, getIcon, importIcon, and removeIcon.

usage notes

Icons are typically used in conjunction with button form fields to display custom graphics. The workflow generally involves:

  1. Importing an icon into the document using Doc.importIcon()
  2. Retrieving the icon using Doc.getIcon() or accessing it through Doc.icons
  3. Applying the icon to a button field using Field.buttonSetIcon()

example:

// Complete workflow for using icons
// 1. Import an icon (user will be prompted to select an image file)
var result = this.importIcon("CompanyLogo")

if (result == 0) {
    // 2. Get the icon reference
    var logoIcon = this.getIcon("CompanyLogo")
    
    // 3. Apply to a button field
    var logoButton = this.getField("LogoButton")
    if (logoButton) {
        logoButton.buttonSetIcon(logoIcon)
    }
}

identity

properties

loginName

SecureTypeAccess
NostringR

Login username of the current user. See name for the username as entered in the Revu preferences.


name

SecureTypeAccess
NostringR

Username as entered in the Revu preferences.


Net.HTTP

Net.HTTP provides HTTP request functionality for making web requests from within PDF JavaScript. This object enables communication with web servers to send and receive data.

Net.HTTP requires elevated privileges to function. Scripts must be trusted or run in a privileged context.

methods

request

Secure
Yes

Performs an HTTP request to a specified URL with configurable options.

request(oRequest)

oRequest: Object containing the request configuration with the following properties:

PropertyTypeRequiredDescription
cVerbstringYesHTTP method such as "GET", "POST", "PUT", "DELETE", etc.
cURLstringYesThe URL to send the request to
aHeadersarrayNoArray of header objects, each containing name and value properties
oRequestobjectNoReadStream object containing the request body data
oHandlerobjectNoObject containing a response callback function. See below.
oAuthenticateobjectNoNot used by Revu

oHandler

The oHandler parameter is an object literal containing a callback function that is called when the HTTP response is received.

PropertyDescription
responseCallback function executed when the HTTP response is received

response

The response callback function receives the following parameters:

  • oStream: ReadStream object containing the response body
  • cURL: The URL that was requested
  • oException: Error object with error and msg properties if an error occurred, null otherwise
  • aHeaders: Array of response header objects, each containing name and value properties

example:

// Simple GET request
Net.HTTP.request({
    cVerb: "GET",
    cURL: "https://api.example.com/data",
    oHandler: {
        response: function(stream, url, exception) {
            if (exception) {
                console.println("Error: " + exception.msg);
            } else {
                var responseText = util.stringFromStream(stream, "utf-8");
                console.println("Response: " + responseText);
            }
        }
    }
});
// POST request with headers and body
var requestBody = util.streamFromString(JSON.stringify({
    name: "Example",
    value: 123
}), "utf-8");

Net.HTTP.request({
    cVerb: "POST",
    cURL: "https://api.example.com/submit",
    aHeaders: [
        { name: "Content-Type", value: "application/json" },
        { name: "Authorization", value: "Bearer token123" }
    ],
    oRequest: requestBody,
    oHandler: {
        response: function(stream, url, exception, headers) {
            if (exception) {
                console.println("Request failed: " + exception.msg);
                return;
            }
            
            // Process response headers
            if (headers) {
                headers.forEach(function(header) {
                    console.println(header.name + ": " + header.value);
                });
            }
            
            // Process response body
            var responseText = util.stringFromStream(stream, "utf-8");
            console.println("Server response: " + responseText);
        }
    }
});

OCG

OCG (Optional Content Group) object represents layers in a PDF file. OCGs control the visibility of content and are referred to as "Layers" within Revu. OCG objects are obtained through the Doc.getOCGs method.

properties

constants

SecureTypeAccess
NoobjectR

Object containing constants used with OCG operations.

Properties of the constants object:

PropertyTypeDescription
intentsobjectIntent constants for OCG purposes
statesobjectState constants for OCG visibility

intents

Properties of the intents object:

PropertyValueDescription
design"Design"Content for design purposes
view"View"Content for interactive viewing

states

Properties of the states object:

PropertyValueDescription
ontrueLayer is visible
offfalseLayer is hidden

example:

var ocgs = this.getOCGs()
if (ocgs != null && ocgs.length > 0) {
    var ocg = ocgs[0]
    console.println(ocg.constants.intents.view) // Prints "View"
    console.println(ocg.constants.states.on)    // Prints true
}

initState

SecureTypeAccess
NobooleanR/W

The initial state of the OCG when the document is first opened. When true, the layer is visible by default. When false, the layer is hidden by default.

example:

var ocgs = this.getOCGs()
if (ocgs != null) {
    ocgs.forEach(function(ocg) {
        if (ocg.name === "Electrical") {
            ocg.initState = false // Hide electrical layer by default
        }
    })
}

locked

SecureTypeAccess
NobooleanR/W

Specifies whether the OCG is locked. When locked, users cannot change the visibility state of the layer through the Revu interface.

example:

var ocgs = this.getOCGs()
if (ocgs != null) {
    ocgs.forEach(function(ocg) {
        if (ocg.name === "Watermark") {
            ocg.locked = true // Prevent users from hiding the watermark
        }
    })
}

name

SecureTypeAccess
NostringR/W

The name of the OCG as it appears in the Layers panel.

example:

var ocgs = this.getOCGs()
if (ocgs != null) {
    ocgs.forEach(function(ocg, index) {
        console.println(`Layer ${index}: ${ocg.name}`)
        // Rename a specific layer
        if (ocg.name === "Layer1") {
            ocg.name = "Structural"
        }
    })
}

state

SecureTypeAccess
NobooleanR/W

The current visibility state of the OCG. When true, the layer is visible. When false, the layer is hidden.

example:

var ocgs = this.getOCGs()
if (ocgs != null) {
    // Toggle all layers
    ocgs.forEach(function(ocg) {
        ocg.state = !ocg.state
    })
    
    // Hide all layers except one
    ocgs.forEach(function(ocg) {
        ocg.state = (ocg.name === "Architectural")
    })
}

methods

getIntent

Secure
No

Returns the intent setting for the OCG.

getIntent()

Returns an array of strings representing the intent(s) of the OCG. Possible values are "View" and "Design".

The intent determines the purpose of the OCG:

  • "View": Content intended for interactive viewing
  • "Design": Content intended for design purposes

An OCG can have multiple intents.

example:

var ocgs = this.getOCGs()
if (ocgs != null && ocgs.length > 0) {
    var ocg = ocgs[0]
    var intents = ocg.getIntent()
    console.println("OCG intents: " + intents.join(", "))
    
    // Check if OCG has view intent
    if (intents.indexOf("View") !== -1) {
        console.println("This layer is intended for viewing")
    }
}

setIntent

Secure
No

Sets the intent for the OCG.

setIntent(aIntents)

aIntents: Array of intent strings. Valid values are "View" and "Design".

example:

var ocgs = this.getOCGs()
if (ocgs != null) {
    ocgs.forEach(function(ocg) {
        if (ocg.name === "Annotations") {
            // Set layer for both viewing and design
            ocg.setIntent(["View", "Design"])
        } else if (ocg.name === "Guidelines") {
            // Set layer for design only
            ocg.setIntent(["Design"])
        }
    })
}

PrintParams

PrintParams object controls the printing options for PDF documents. PrintParams objects are obtained through the Doc.getPrintParams method and are used with the Doc.print method.

properties

binaryOK

SecureTypeAccess
NobooleanR/W

Not supported by Revu. Exists for compatibility reasons.


bitmapDPI

SecureTypeAccess
NonumberR/W

Not supported by Revu. Exists for compatibility reasons.


booklet

SecureTypeAccess
NoobjectR/W

Not supported by Revu. Exists for compatibility reasons.


colorOverride

SecureTypeAccess
NonumberR/W

Overrides color printing settings. See constants.colorOverrides for valid values.

example:

var pp = this.getPrintParams()
pp.colorOverride = pp.constants.colorOverrides.gray // Force grayscale printing
this.print(pp)

colorProfile

SecureTypeAccess
NostringR/W

Not supported by Revu. Exists for compatibility reasons.


constants

SecureTypeAccess
NoobjectR

Object containing constants used with PrintParams operations.

constants

PropertyTypeDescription
bookletBindingsobjectBooklet binding edge options
bookletDuplexModeobjectBooklet duplex printing modes
colorOverridesobjectColor override options
fontPoliciesobjectFont download policies
handlingobjectPage handling options
interactionLevelobjectUser interaction levels
nUpPageOrdersobjectPage ordering for N-up printing
printContentsobjectContent to print
flagValuesobjectAdvanced printing flags
rasterFlagValuesobjectRaster printing flags
subsetsobjectPage subset options
tileMarksobjectTile mark positions
usagesobjectUsage options for various features

bookletBindings

PropertyValueDescription
Left0Bind on left edge
Right1Bind on right edge
LeftTall2Bind on left edge (tall pages)
RightTall3Bind on right edge (tall pages)

bookletDuplexMode

PropertyValueDescription
BothSides0Print on both sides
FrontSideOnly1Print on front side only
BackSideOnly2Print on back side only

colorOverrides

PropertyValueDescription
auto0Use printer default
gray1Force grayscale
mono2Force monochrome

fontPolicies

PropertyValueDescription
jobStart0Download fonts at start of job
pageRange1Download fonts for page range
everyPage2Download fonts for every page

handling

PropertyValueDescription
none1No special handling
fit2Fit to page
shrink3Shrink oversized pages
tileLarge4Tile large pages
tileAll5Tile all pages
nUp6Multiple pages per sheet
booklet7Booklet printing

interactionLevel

PropertyValueDescription
full1Show print dialog
automatic2Print with progress dialog
silent3Print silently

nUpPageOrders

PropertyValueDescription
Horizontal1Left to right, top to bottom
HorizontalReversed2Right to left, top to bottom
Vertical3Top to bottom, left to right

printContents

PropertyValueDescription
doc1Document only
docAndComments2Document and comments
formFieldsOnly3Form fields only

subsets

PropertyValueDescription
all-3All pages
even-5Even pages only
odd-4Odd pages only

tileMarks

PropertyValueDescription
none0No tile marks
west1Western (left) style marks
east2Eastern (right) style marks

example:

var pp = this.getPrintParams()
pp.interactive = pp.constants.interactionLevel.automatic
pp.pageHandling = pp.constants.handling.fit
pp.pageSubset = pp.constants.subsets.odd
this.print(pp)

downloadFarEastFonts

SecureTypeAccess
NobooleanR/W

Not supported by Revu. Exists for compatibility reasons.


fileName

SecureTypeAccess
NostringR/W

Output filename when printing to file. Default is empty string.

example:

var pp = this.getPrintParams()
pp.fileName = "output.ps" // Print to PostScript file
pp.printerName = "PostScript File"
this.print(pp)

firstPage

SecureTypeAccess
NonumberR/W

0-based index of the first page to print. Default is 0.

example:

var pp = this.getPrintParams()
pp.firstPage = 2  // Start printing from page 3
pp.lastPage = 5   // End at page 6
this.print(pp)

flags

SecureTypeAccess
NonumberR/W

Not supported by Revu. Exists for compatibility reasons.


fontPolicy

SecureTypeAccess
NonumberR/W

Not supported by Revu. Exists for compatibility reasons.


gradientDPI

SecureTypeAccess
NonumberR/W

Not supported by Revu. Exists for compatibility reasons.


interactive

SecureTypeAccess
NonumberR/W

Level of user interaction during printing. See constants.interactionLevel for valid values. Default is full.

example:

var pp = this.getPrintParams()
pp.interactive = pp.constants.interactionLevel.silent // Print without dialogs
this.print(pp)

lastPage

SecureTypeAccess
NonumberR/W

0-based index of the last page to print. Default is the last page in the document.

example:

var pp = this.getPrintParams()
pp.firstPage = 0
pp.lastPage = 9  // Print first 10 pages
this.print(pp)

nUpAutoRotate

SecureTypeAccess
NobooleanR/W

Not supported by Revu. Exists for compatibility reasons.


nUpNumPagesH

SecureTypeAccess
NonumberR/W

Not supported by Revu. Exists for compatibility reasons.


nUpNumPagesV

SecureTypeAccess
NonumberR/W

Not supported by Revu. Exists for compatibility reasons.


nUpPageBorder

SecureTypeAccess
NobooleanR/W

Not supported by Revu. Exists for compatibility reasons.


nUpPageOrder

SecureTypeAccess
NonumberR/W

Not supported by Revu. Exists for compatibility reasons.


pageHandling

SecureTypeAccess
NonumberR/W

Page sizing and handling option. See constants.handling for valid values. Default is fit.

example:

var pp = this.getPrintParams()
pp.pageHandling = pp.constants.handling.shrink // Shrink oversized pages
this.print(pp)

pageSubset

SecureTypeAccess
NonumberR/W

Subset of pages to print. See constants.subsets for valid values. Default is all.

example:

var pp = this.getPrintParams()
pp.pageSubset = pp.constants.subsets.even // Print even pages only
this.print(pp)

printAsImage

SecureTypeAccess
NobooleanR/W

Specifies whether to rasterize pages as images before printing. Default is false.

example:

var pp = this.getPrintParams()
pp.printAsImage = true // Print as image for compatibility
pp.bitmapDPI = 300
this.print(pp)

printContent

SecureTypeAccess
NonumberR/W

Not supported by Revu. Exists for compatibility reasons.


printerName

SecureTypeAccess
NostringR/W

Name of the printer to use. Empty string uses the default printer. Default is "".

example:

var pp = this.getPrintParams()
pp.printerName = "HP LaserJet" // Specific printer
this.print(pp)

// Use default printer
pp.printerName = ""
this.print(pp)

psLevel

SecureTypeAccess
NonumberR/W

Not supported by Revu. Exists for compatibility reasons.


rasterFlags

SecureTypeAccess
NonumberR/W

Not supported by Revu. Exists for compatibility reasons.


reversePages

SecureTypeAccess
NobooleanR/W

Specifies whether to print pages in reverse order. Default is false.

example:

var pp = this.getPrintParams()
pp.reversePages = true // Print last page first
this.print(pp)

tileLabel

SecureTypeAccess
NobooleanR/W

Not supported by Revu. Exists for compatibility reasons.


tileMark

SecureTypeAccess
NonumberR/W

Not supported by Revu. Exists for compatibility reasons.


tileOverlap

SecureTypeAccess
NonumberR/W

Not supported by Revu. Exists for compatibility reasons.


tileScale

SecureTypeAccess
NonumberR/W

Not supported by Revu. Exists for compatibility reasons.


transparencyLevel

SecureTypeAccess
NonumberR/W

Not supported by Revu. Exists for compatibility reasons.


usePrinterCRD

SecureTypeAccess
NonumberR/W

Not supported by Revu. Exists for compatibility reasons.


useT1Conversion

SecureTypeAccess
NonumberR/W

Not supported by Revu. Exists for compatibility reasons.


ReadStream

ReadStream object provides access to data streams for reading embedded file contents and other stream data within PDF files. The stream reads data as hexadecimal-encoded strings.

methods

read

Secure
No

Reads bytes from the stream and returns them as a hexadecimal-encoded string.

read(nBytes)

nBytes: Number of bytes to read from the stream

Returns a hexadecimal-encoded string representing the bytes read. Each byte is represented by two hexadecimal characters. If the end of the stream is reached, the stream is automatically closed and subsequent calls will return an empty string.

example:

// Read an embedded text file
var stream = this.getDataObjectContents("data.txt")
var hexData = stream.read(100) // Read first 100 bytes as hex string
console.println(hexData)

// Convert entire stream to string using util helper
var stream2 = this.getDataObjectContents("data.txt")
var text = util.stringFromStream(stream2, "utf-8")
console.println(text)

Span

Span objects represent formatted text segments within rich text fields. They contain style and formatting information for portions of text in rich text form fields. Span objects are used with the richValue property of text fields that have richText enabled.

example:

var field = this.getField("richTextField")
field.richText = true
var spans = [
    {text: "Bold text", fontWeight: 700},
    {text: " and ", fontWeight: 400},
    {text: "italic text", fontStyle: "italic"}
]
field.richValue = spans

properties

alignment

SecureTypeAccess
NostringR/W

The horizontal alignment of the text within the span.

Valid values:

  • "left"
  • "center"
  • "right"

example:

var span = {
    text: "Centered text",
    alignment: "center"
}

fontFamily

SecureTypeAccess
NoarrayR/W

An array containing the font family name(s) for the span. The first element is the primary font family. Additional elements can specify fallback fonts.

Default value is ["sans-serif"].

example:

var span = {
    text: "Custom font text",
    fontFamily: ["Helvetica", "Arial", "sans-serif"]
}

fontStretch

SecureTypeAccess
NostringR/W

The font stretch value for the span text.

Valid values:

  • "ultra-condensed"
  • "extra-condensed"
  • "condensed"
  • "semi-condensed"
  • "normal" (default)
  • "semi-expanded"
  • "expanded"
  • "extra-expanded"
  • "ultra-expanded"

example:

var span = {
    text: "Condensed text",
    fontStretch: "condensed"
}

fontStyle

SecureTypeAccess
NostringR/W

The font style for the span text.

Valid values:

  • "normal" (default)
  • "italic"

example:

var span = {
    text: "Italic text",
    fontStyle: "italic"
}

fontWeight

SecureTypeAccess
NonumberR/W

The font weight for the span text. Values greater than 400 are considered bold.

Common values:

  • 400 - Normal (default)
  • 700 - Bold

example:

var span = {
    text: "Bold text",
    fontWeight: 700
}

strikethrough

SecureTypeAccess
NobooleanR/W

When true, the text has a line through it. Default is false.

example:

var span = {
    text: "Strikethrough text",
    strikethrough: true
}

subscript

SecureTypeAccess
NobooleanR/W

When true, the text appears as subscript. Default is false. Cannot be true if superscript is true.

example:

var span = {
    text: "2",
    subscript: true
}
// Creates H₂O when combined with other spans

superscript

SecureTypeAccess
NobooleanR/W

When true, the text appears as superscript. Default is false. Cannot be true if subscript is true.

example:

var span = {
    text: "2",
    superscript: true
}
// Creates x² when combined with other spans

text

SecureTypeAccess
NostringR/W

The actual text content of the span.

example:

var span = {
    text: "This is the text content"
}

textColor

SecureTypeAccess
NoobjectR/W

The color of the text. Value is a color array in the same format as the color object. Default is black.

example:

var span = {
    text: "Red text",
    textColor: color.red
}

// Or using RGB array
var span = {
    text: "Blue text",
    textColor: ["RGB", 0, 0, 1]
}

textSize

SecureTypeAccess
NonumberR/W

The font size of the text in points. Default is 12.

example:

var span = {
    text: "Large text",
    textSize: 18
}

underline

SecureTypeAccess
NobooleanR/W

When true, the text is underlined. Default is false.

example:

var span = {
    text: "Underlined text",
    underline: true
}

usage examples

Creating rich text with multiple spans

var field = this.getField("richTextField")
field.richText = true

// Create formatted text with multiple styles
field.richValue = [
    {
        text: "Important: ",
        fontWeight: 700,
        textColor: color.red,
        textSize: 14
    },
    {
        text: "This document expires on ",
        fontWeight: 400,
        textSize: 12
    },
    {
        text: "December 31, 2024",
        fontWeight: 700,
        underline: true,
        textSize: 12
    }
]

Chemical formula with subscripts

var field = this.getField("formulaField")
field.richText = true

field.richValue = [
    {text: "H", textSize: 12},
    {text: "2", subscript: true, textSize: 12},
    {text: "SO", textSize: 12},
    {text: "4", subscript: true, textSize: 12}
]

Mathematical expression with superscripts

var field = this.getField("mathField")
field.richText = true

field.richValue = [
    {text: "E = mc", textSize: 12},
    {text: "2", superscript: true, textSize: 12}
]

Template

Template objects represent named pages that can be spawned (instantiated) multiple times within a PDF document. Templates are useful for creating repetitive content like forms, headers, or any reusable page content. Templates are hidden pages that serve as a blueprint for creating new pages or overlaying content on existing pages.

properties

hidden

SecureTypeAccess
NobooleanR/W

Controls the visibility of the template. When true, the template page is hidden from normal view. Templates are typically hidden to prevent them from appearing as regular pages in the document.

example:

var template = this.getTemplate("MyTemplate")
template.hidden = false // Make the template visible as a regular page

name

SecureTypeAccess
NostringR

The name of the template. This is the identifier used to reference the template within the document.

example:

var template = this.getTemplate("InvoiceTemplate")
console.println("Template name: " + template.name) // Prints "InvoiceTemplate"

methods

spawn

Secure
No

Creates a new instance of the template, either as a new page or as an overlay on an existing page.

spawn(nPage, bRename, bOverlay, oXObject)

nPage: [optional] 0-based page number where the template will be spawned. If overlaying (bOverlay is true), this is the page to overlay onto. If inserting (bOverlay is false), the new page is inserted after this page number. Default is the last page of the document.

bRename: [optional] When true, automatically renames form fields in the spawned template to avoid naming conflicts with existing fields. This is important when spawning multiple instances of the same template. Default is true.

bOverlay: [optional] When true, overlays the template content onto an existing page. When false, inserts the template as a new page. Default is false.

oXObject: [optional] JavaScript object containing field name/value pairs to populate form fields in the spawned template. The property names should match the field names in the template.

example:

// Get the template
var template = this.getTemplate("OrderForm")

// Spawn as a new page after page 5
template.spawn(5, true, false)

// Spawn as an overlay on page 2 with field data
var formData = {
    "customer_name": "John Smith",
    "order_date": "2024-01-15",
    "order_number": "ORD-001"
}
template.spawn(2, true, true, formData)

// Spawn multiple instances with different data
for (var i = 0; i < 3; i++) {
    var data = {
        "invoice_no": "INV-" + (1000 + i),
        "page_number": i + 1
    }
    template.spawn(this.numPages, true, false, data)
}

util

util is a static object that provides various utility functions for formatting dates, numbers, strings, and handling file streams.

methods

printd

Secure
No

Formats a date according to a specified format string.

util.printd(cFormat, oDate, bXFAPicture)

cFormat: Format string for the date. Uses standard date format patterns where:

  • m - Month (1-12)
  • mm - Month with leading zero (01-12)
  • mmm - Abbreviated month name
  • mmmm - Full month name
  • d - Day (1-31)
  • dd - Day with leading zero (01-31)
  • yy - Two digit year
  • yyyy - Four digit year
  • h - Hour (12-hour format)
  • hh - Hour with leading zero (12-hour format)
  • H - Hour (24-hour format)
  • HH - Hour with leading zero (24-hour format)
  • M - Minute
  • MM - Minute with leading zero
  • s - Second
  • ss - Second with leading zero
  • tt - AM/PM designator

oDate: JavaScript Date object to format

bXFAPicture: [optional] Not used by Revu. Default is false

Returns the formatted date string

example:

var d = new Date()
console.println(util.printd("mm/dd/yyyy", d)) // Prints "01/15/2024"
console.println(util.printd("mmmm d, yyyy", d)) // Prints "January 15, 2024"
console.println(util.printd("yyyy-mm-dd HH:MM:ss", d)) // Prints "2024-01-15 14:30:45"

printf

Secure
No

Formats one or more values according to a format string, similar to the C printf function.

util.printf(cFormat, ...arguments)

cFormat: Format string containing format specifiers

arguments: Values to be formatted according to the format string

Format specifiers:

  • %s - String
  • %d - Integer
  • %f - Floating point number
  • %x - Hexadecimal (uppercase)
  • %,0d - Integer with thousands separator
  • %,1d - Integer without thousands separator
  • %,2d - Integer with period as thousands separator
  • %,3d - Integer with period as thousands separator and comma as decimal
  • %,4d - Integer with apostrophe as thousands separator

Additional format options:

  • Width: Number specifying minimum field width (e.g., %10s)
  • Precision: . followed by number for decimal places (e.g., %.2f)
  • Flags:
    • + - Always show sign for numbers
    • - Prefix positive numbers with space
    • 0 - Pad with zeros
    • # - Alternate form

Returns the formatted string

example:

console.println(util.printf("Name: %s, Age: %d", "John", 25))
// Prints "Name: John, Age: 25"

console.println(util.printf("Price: $%,0.2f", 1234.5))
// Prints "Price: $1,234.50"

console.println(util.printf("Hex: %x", 255))
// Prints "Hex: FF"

console.println(util.printf("%+d, % d, %05d", 42, 42, 42))
// Prints "+42,  42, 00042"

printx

Secure
No

Formats a string according to a template pattern, useful for formatting phone numbers, social security numbers, and other structured data.

util.printx(cFormat, cSource)

cFormat: Template string with special characters:

  • ? - Matches any character
  • X - Matches any alphanumeric character (skips non-alphanumeric)
  • A - Matches any letter (skips non-letters)
  • 9 - Matches any digit (skips non-digits)
  • * - Matches all remaining characters
  • \ - Escape character for literals
  • > - Converts subsequent characters to uppercase
  • < - Converts subsequent characters to lowercase
  • = - Preserves case of subsequent characters

cSource: Source string to format

Returns the formatted string

example:

console.println(util.printx("(999) 999-9999", "5551234567"))
// Prints "(555) 123-4567"

console.println(util.printx("999-99-9999", "123456789"))
// Prints "123-45-6789"

console.println(util.printx(">AAA-999", "abc123"))
// Prints "ABC-123"

console.println(util.printx("\\*999\\*", "456"))
// Prints "*456*"

console.println(util.printx("?-?-?", "ABC"))
// Prints "A-B-C"

readFileIntoStream

Secure
Yes

Reads a file from disk into a stream. This function requires elevated privileges.

util.readFileIntoStream(cDIPath, bEncodeBase64)

cDIPath: [optional] Device-independent path to the file. If not specified, the user is prompted to select a file.

bEncodeBase64: [optional] When true, encodes the file contents as Base64. Default is false

Returns a ReadStream object containing the file contents, or null if the operation fails

example:

// Prompt user to select a file
var stream = util.readFileIntoStream()
if (stream) {
    var contents = util.stringFromStream(stream)
    console.println(contents)
}

// Read specific file (requires elevated privileges)
var stream = util.readFileIntoStream("/c/data/config.txt")

// Read and encode as Base64
var stream = util.readFileIntoStream("/c/data/image.png", true)

scand

Secure
No

Parses a date string according to a specified format and returns a Date object.

util.scand(cFormat, cDate)

cFormat: Format string describing the expected date format (uses same format as printd)

cDate: String containing the date to parse

Returns a JavaScript Date object if parsing succeeds, throws an error if parsing fails

example:

var date = util.scand("mm/dd/yyyy", "01/15/2024")
console.println(date) // Date object for January 15, 2024

var date2 = util.scand("yyyy-mm-dd", "2024-01-15")
console.println(date2) // Date object for January 15, 2024

var date3 = util.scand("mmmm d, yyyy", "January 15, 2024")
console.println(date3) // Date object for January 15, 2024

streamFromString

Secure
No

Creates a stream from a string with the specified character encoding.

util.streamFromString(cString, cCharSet)

cString: String to convert to a stream

cCharSet: [optional] Character encoding. Default is "utf-8". Supported values:

  • "utf-8"
  • "utf-16"
  • "Shift-JIS"
  • "BigFive"
  • "GBK"
  • "UHC"

Returns a ReadStream object containing the encoded string

example:

var stream = util.streamFromString("Hello World")
// Creates a UTF-8 encoded stream

var stream2 = util.streamFromString("こんにちは", "Shift-JIS")
// Creates a Shift-JIS encoded stream

// Use with other functions that expect streams
this.setDataObjectContents("data.txt", stream)

stringFromStream

Secure
No

Converts a stream to a string using the specified character encoding.

util.stringFromStream(oStream, cCharSet)

oStream: ReadStream object to convert

cCharSet: [optional] Character encoding. Default is "utf-8". Supported values:

  • "utf-8"
  • "utf-16"
  • "Shift-JIS"
  • "BigFive"
  • "GBK"
  • "UHC"

Returns the decoded string

example:

// Read a data object as a string
var stream = this.getDataObjectContents("textfile.txt")
var text = util.stringFromStream(stream)
console.println(text)

// Read with specific encoding
var stream2 = this.getDataObjectContents("japanese.txt")
var text2 = util.stringFromStream(stream2, "Shift-JIS")
console.println(text2)

Chapter 6: Use Cases

Stamps

Interactive Stamps

Stamps in Revu are more than simple annotations—they're mini PDF files that can contain form fields and JavaScript. When you apply a stamp to a document, Revu executes any calculation scripts within the stamp, allowing for dynamic behavior and user interaction.

How Stamps Execute

When a stamp is placed on a PDF:

  1. Form fields within the stamp become active
  2. Calculation scripts execute with event.source.forReal set to true
  3. Any dialogs defined in the stamp appear
  4. Form fields populate with the collected data
  5. The resulting PDF file is flattened as a static stamp annotation on the target PDF

The event.source.forReal property is key—it's only true during stamp placement, allowing your code to distinguish between the initial application and other calculation events.

Stamp Architecture

An interactive stamp consists of two JavaScript components:

Document-Level Script

This defines your stamp's configuration and behavior. Users modify this section to customize the stamp for their needs. It includes field definitions, default values, and dialog configurations.

Calculation Field Script

A hidden form field with calculation JavaScript that runs when the stamp is applied. This handles dialog creation, user input collection, and field population. Users rarely need to modify this.

The Builder Object

The document-level script centers around a builder object that defines what information your stamp collects:

var builder = {
    // Text fields that will appear in the dialog
    textBoxes: [
        { 
            field: "CheckedBy",      // Must match text field name in stamp PDF
            description: "Checked by:", // Label shown in dialog
            default: function() { return Collab.user; } // Dynamic default
        },
        { 
            field: "Date", 
            description: "Date:", 
            default: function() {  
                var curDate = new Date();
                return (curDate.getMonth() + 1) + "/" + 
                       curDate.getDate() + "/" + 
                       curDate.getFullYear();
            } 
        },
        { 
            field: "SubmittalNumber", 
            description: "Submittal #:", 
            default: function() { return ""; } // Static default
        }
    ],
    
    // Radio button group for status selection
    radioGroup: "Status",  // Must match radio group name in stamp PDF
    radioButtons: [
        { value: "Approved", description: "Approved" },
        { value: "Revise", description: "Revise" },
        { value: "Rejected", description: "Rejected" }
    ],
    radioErrorMsg: "Please select a status"
}

Critical: Every field referenced in JavaScript must have a corresponding form field in the stamp PDF with an exactly matching name. If these don't match, the stamp won't populate correctly.

Default Value Functions

Default values can be static or dynamic. Dynamic defaults are particularly useful:

// Static default
{ field: "Department", description: "Department:", default: function() { return "Engineering"; } }

// Dynamic default using current user
{ field: "Reviewer", description: "Reviewer:", default: function() { return Collab.user; } }

// Dynamic default using current date/time
{ field: "Timestamp", description: "Time:", default: function() { 
    var now = new Date();
    return now.toLocaleTimeString();
} }

Accessing the Target Document

One important distinction when working with stamps is understanding the scope:

  • this refers to the stamp PDF itself
  • event.source refers to the field triggering the calculation
  • event.source.source refers to the target document being stamped

This allows stamps to capture information from the document they're being applied to:

var builder = {
    textBoxes: [
        { 
            field: "TargetFileName", 
            description: "Document:", 
            default: function() { 
                // Get filename of document being stamped
                var path = event.source.source.path;
                return path.split("/").pop().split("\\").pop();
            } 
        },
        { 
            field: "PageInfo", 
            description: "Page:", 
            default: function() { 
                var doc = event.source.source;
                var currentPage = doc.pageNum + 1;
                var totalPages = doc.numPages;
                return currentPage + " of " + totalPages;
            } 
        }
    ]
};

Adding Dropdowns

You can include dropdown menus for predefined selections:

var builder = {
    // ... other properties ...
    
    popupGroup: "Project",  // Must match popup field in stamp PDF
    listItems: [{
        popupItems: {
            "Project Alpha": -1,    // -1 means not selected by default
            "Project Beta": -1,
            "Project Gamma": 1,     // 1 means selected by default
            "Project Delta": -1
        }
    }]
}

Field Naming Requirements

Use clear, consistent naming for your fields:

  • Use PascalCase: ReviewerName, ApprovalDate
  • Avoid spaces and special characters
  • Match names exactly between JavaScript and PDF form fields
  • Use descriptive names that indicate purpose

Complete Working Example

Here's a complete engineering review stamp that demonstrates the key concepts:

// DOCUMENT LEVEL SCRIPT - Customize this for your needs

var builder = {
    // Text input fields
    textBoxes: [
        { 
            field: "ReviewedBy", 
            description: "Reviewed by:", 
            default: function() { 
                return Collab.user || "Unknown User"; 
            } 
        },
        { 
            field: "ReviewDate", 
            description: "Date:", 
            default: function() {  
                var curDate = new Date();
                return (curDate.getMonth() + 1) + "/" + 
                       curDate.getDate() + "/" + 
                       curDate.getFullYear();
            } 
        },
        { 
            field: "SubmittalNumber", 
            description: "Submittal #:", 
            default: function() { return ""; } 
        },
        { 
            field: "DrawingNumber", 
            description: "Drawing #:", 
            default: function() { return ""; } 
        }
    ],
    
    // Radio button group for approval status
    radioGroup: "ApprovalStatus",
    radioButtons: [
        { value: "Approved", description: "Approved as Submitted" },
        { value: "ApprovedAsNoted", description: "Approved as Noted" },
        { value: "ReviseResubmit", description: "Revise and Resubmit" },
        { value: "Rejected", description: "Rejected" }
    ],
    radioErrorMsg: "Please select an approval status",
    
    // Dropdown for discipline
    popupGroup: "Discipline",
    listItems: [{
        popupItems: {
            "Architectural": -1,
            "Structural": -1,
            "Mechanical": -1,
            "Electrical": -1,
            "Plumbing": -1,
            "Civil": -1
        }
    }]
};

The calculation field script that executes this builder is typically hidden and handles the dialog display and field population automatically.

Common Issues and Solutions

Fields Not Populating

Field names in JavaScript don't match PDF form field names exactly. Verify spelling, capitalization, and spacing.

Dialog Not Appearing

Syntax error in the document-level script. Check the JavaScript console for errors.

Default Values Not Working

Error in default value function. Check the console and ensure all referenced properties exist.

Radio Buttons Not Saving

Radio button export values don't match JavaScript values. Check the "Choice" property of each radio button.

Debugging Stamps

When developing stamps, use these techniques:

// Console logging to trace execution
default: function() {
    console.println("Getting user name...");
    var userName = Collab.user;
    console.println("User name: " + userName);
    return userName || "Unknown";
}

// Alert debugging for variable values
app.alert("Current value: " + myVariable);

// Verify fields exist
var field = this.getField("MyFieldName");
if (!field) {
    console.println("Field not found: MyFieldName");
}

Summary

Interactive stamps provide a powerful way to standardize data collection in your PDF workflows. Remember:

  • Field names must match exactly between JavaScript and PDF
  • Use event.source.source to access the target document
  • The document-level script is what users customize
  • Test thoroughly before deployment