PDFOne .NET
Powerful all-in-one PDF library for .NET
Compatibility
VS 2005/2008/2010/2012/2013

An Acrobat Javascript primer with simple PDF examples

Learn how to use JavaScript in your PDF documents and forms.
By V. Subhash

Most people associate JavaScript with Web browsers and HTML pages. (Not many people remember that Internet Explorer supported VBScript as an alternative for JavaScript.) JavaScript has also been used on the server-side in Classic ASP as an alternative for VBScript. JavaScript on the server-side is not a recent phenomenon with Node.js and other technologies. The well-known Adobe Flash player runs a form of JavaScript called ActionScript. At least most virus writers know that JavaScript can be run from your Windows command prompt.

Although JavaScript requires a scripting host application, it is not tied to any particular implementation. The language is developed and standardized by the ECMA independently of the scripting hosts.

The scripting host in a Web browser exposes the "host objects" such as window, document (DOM) and location objects to the JavaScript engine. Similarly, in Adobe Reader, Adobe Acrobat and other applications, the viewer exposes several host objects to the JavaScript engine. These host objects are described in two documents:

HTML+JavaScript or DHTML was once sold to the general public as "HTML with steroids". JavaScript can indeed super-charge your PDF documents. In this article, we will see a bit of what you can do with it. I have used PDFOne .NET to add JavaScript to PDF documents. You can do the same with any PDF library such as PDFOne (for Java) and PDFtoolkit VCL.

A "Hello, World!" Example

This code snippet uses the app object's alert() method. This alert has been added to the document's "Open" viewer application event. There are other situations where you can add such JavaScript scripts - "close", "save", or "print".

static void create_PdfWithDocumentOpenAction() {
  PDFDocument doc = new PDFDocument(PDFOne_License.KEY);
  doc.AddOpenActionJavaScript("app.alert('Hello, World!')");
  doc.Save("Hello.pdf");
  doc.Close();
}

Let us look up the app object in the API Reference.

Now, using the API reference, the above alert can be made less foreboding.

static void create_PdfWithDocumentOpenAction() {
  PDFDocument doc = new PDFDocument(PDFOne_License.KEY);
  doc.AddOpenActionJavaScript(
  	"app.alert('Hello, World!', 3, 0, 'Acrobat JavaScript Examples');");
  doc.Save("Hello.pdf");
  doc.Close();
}

Add JavaScript to PDF objects

JavaScript scripts can be added to PDF objects such as annotations, form fields and even bookmarks. In the following example, a JavaScript script has been added to a link annotation.

static void create_PDFJavaScriptLinkAnnotation() {
  // Create a PDF document
  PDFDocument doc = new PDFDocument(PDFOne_License.KEY);
  doc.MeasurementUnit = PDFMeasurementUnit.Inches;

  // Create a link annotation
  PDFLinkAnnot la1 =
    new PDFLinkAnnot(
      new RectangleF(1f, 1f, 2f, 0.3f)); // annotation rectangle

  // Add JavaScript PDF action to the annotation
  la1.AddActionJavaScript(
    "app.alert('Page count is ' + this.numPages);");

  // Write text where the link will be active
  doc.WriteText("Click here for page count", 1f, 1f);
  
  // Add the annotation to document
  doc.AddAnnot(la1);

  // Save document
  doc.Save("link-annotation1.pdf");
}

This JavaScript script uses the this object where it refers to the Document object. Document has a numPages property for providing the page count.

BTW, this refers to different things in different places. Please read the documentation to avoid making mistakes. Another thing to note is that in Adobe Reader, the document is considered read-only with limited scope for modification. Any JavaScript code that tries to make permanent changes to a document will fail or require the end-user to save change to a new file.

I know what you are thinking. What if you commit errors in your JavaScript scripts? Well, you can check the console.

JavaScript Error Console

Adobe Reader and Adobe Acrobat have an error console. You can enable it from Preferences from the menu or launch it using its namesake console object.

static void create_PdfWithConsoleWindowOpen() {
  PDFDocument doc = new PDFDocument(PDFOne_License.KEY);
  doc.AddOpenActionJavaScript(
    "console.show(); console.clear(); console.println('How are ya doing!');");
  doc.Save("Hello_de_console.pdf");
  doc.Close();
}

How to get something?

Web programmers are familiar with the infamous document.getElementById() method. Does Acrobat JavaScript have something similar? There are several. The following example uses the getField() method to grab a push button form field and add some behaviour to it at startup.

static void create_PdfWithPrintCloseButtons() {
  PDFDocument doc = new PDFDocument(PDFOne_License.KEY);
  doc.MeasurementUnit = PDFMeasurementUnit.Inches;

  // Create a "Close" button
  PDFFormPushButton btn1 = 
    new PDFFormPushButton(new RectangleF(1f, 1f, 2f, 0.3f));
  btn1.NormalCaption = "Close";
  btn1.FieldName = "btn1";
  btn1.ToolTip = "Closes this document";
  doc.AddFormField(btn1);

  // Create a "Print" button
  PDFFormPushButton btn2 = 
    new PDFFormPushButton(new RectangleF(4f, 1f, 2f, 0.3f));
  btn2.NormalCaption = "Print";
  btn2.FieldName = "btn2";
  btn2.ToolTip = "Prints this document";
  doc.AddFormField(btn2);

  // Add button behaviour at startup
  doc.AddOpenActionJavaScript(
    "var oBtn1 = this.getField('btn1'); "+
    "oBtn1.setAction('MouseDown', 'this.closeDoc()'); " +
    "var oBtn2 = this.getField('btn2'); " +
    "oBtn2.setAction('MouseDown', 'this.print()'); ");

  // Save document
  doc.Save("Le_boutons_de_JavaScript.pdf");
  doc.Close();
}

PDF Form Validation With JavaScript

After you "get" a form field, you can evaluate its value using the valueAsString property. If you find the form fields to be valid, you can submit the form using Document.submitForm() method.

static void create_PDFWithFormValidation() {
  PDFDocument doc = new PDFDocument(PDFOne_License.KEY);
  doc.OpenAfterCreate = true;
  doc.MeasurementUnit = PDFMeasurementUnit.Inches;

  // Create a text form field
  PDFFormTextField tf = new PDFFormTextField(new RectangleF(1f, 1f, 1f, 0.3f));
  tf.FieldName = "FullName";
  tf.BackgroundColor = Color.LightGray;
  tf.NameAsUnicode = false;

  // Create a push button form field
  PDFFormPushButton pb = new PDFFormPushButton(new RectangleF(1f, 2f, 1f, 0.3f));
  pb.FieldName = "SubmitButton";
  pb.ActionType = PDFFormFieldActionType.Javascript_Action;
  pb.NormalCaption = "Submit";
  pb.JavaScript = 
    "var oNameField = this.getField('FullName'); " + 
    "if (oNameField.valueAsString.length > 2) { " + 
    "  var arFields = new Array('FullName'); " +
    "  this.submitForm({ " +
    "      cURL: 'http://www.gnostice.com/newsletters/demos/200804/forms_test.asp', " +
    "      aFields: arFields, " +
    "      cSubmitAs: 'HTML', " + 
    "    }); " + 
    "} else { " + 
    "   app.alert('Nhyet! Nhyet! Nhyet!');" + 
    "}";
      
  // Add form fields to the document
  doc.AddFormField(tf);
  doc.AddFormField(pb);
        
  doc.Save("Valider_le_form.pdf");
  doc.Close();
}

Caveat emptor

Running JavaScript in PDF documents is great, no doubt, but you should not rely on it without a fallback mechanism. For example, if you are using JavaScript to do form validation, then you still need to do server-side validation. Not all PDF viewer applications have a JavaScript engine. The PDF/A standard expressly forbids JavaScript. Users may also disable JavaScript in their viewer application. Digital signatures may also add their own complications to the mess. Worst of all, it is not all that easy to add JavaScript or debug it. Gnostice wishes you good luck in your personal forays into AcroJS.

Further Reading

---o0O0o---

Our .NET Developer Tools
Gnostice Document Studio .NET

Multi-format document-processing component suite for .NET developers.

PDFOne .NET

A .NET PDF component suite to create, edit, view, print, reorganize, encrypt, annotate, and bookmark PDF documents in .NET applications.

Our Delphi/C++Builder developer tools
Gnostice Document Studio Delphi

Multi-format document-processing component suite for Delphi/C++Builder developers, covering both VCL and FireMonkey platforms.

eDocEngine VCL

A Delphi/C++Builder component suite for creating documents in over 20 formats and also export reports from popular Delphi reporting tools.

PDFtoolkit VCL

A Delphi/C++Builder component suite to edit, enhance, view, print, merge, split, encrypt, annotate, and bookmark PDF documents.

Our Java developer tools
Gnostice Document Studio Java

Multi-format document-processing component suite for Java developers.

PDFOne (for Java)

A Java PDF component suite to create, edit, view, print, reorganize, encrypt, annotate, bookmark PDF documents in Java applications.

Our Platform-Agnostic Cloud and On-Premises APIs
StarDocs

Cloud-hosted and On-Premises REST-based document-processing and document-viewing APIs

Privacy | Legal | Feedback | Newsletter | Blog | Resellers © 2002-2023 Gnostice Information Technologies Private Limited. All rights reserved.