9.8.  Extract JavaScript to a Text File

This utility extracts JavaScript from a PDF document and writes it to a text file, which can be used in PDFUnit tests as described in chapter 3.14: “JavaScript”.

Program Start

::
:: Extract JavaScript from a PDF document into a text file.
::

@echo off
setlocal
set CLASSPATH=./lib/pdfunit-2015.10/*;%CLASSPATH%
set CLASSPATH=./lib/itext-5.5.1/*;%CLASSPATH%
set CLASSPATH=./lib/bouncycastle-jdk15on-150/*;%CLASSPATH%

set TOOL=com.pdfunit.tools.ExtractJavaScript
set OUT_DIR=./tmp
set IN_FILE=javaScriptForFields.pdf
set PASSWD=

java  %TOOL%  %IN_FILE%  %OUT_DIR%  %PASSWD%
endlocal

Input

The file javaScriptForFields.pdf used in chapter 9.3: “Extract Field Information to XML” contains the fields nameField, ageField and comment which are all associated with JavaScript.

Inside the Java program which creates the PDF document, the following JavaScript code belongs to the field ageField:

String scriptCodeCheckAge = "var ageField = this.getField('ageField');"
       + "ageField.setAction('Validate','checkAge()');"
       + ""
       + "function checkAge() {"
       + "  if(event.value < 12) {"
       + "    app.alert('Warning! Applicant\\'s age can not be younger than 12.');"
       + "    event.value = 12;"
       + "  }"
       + "}"
;

Output

The output file _javascript_javaScriptForFields.out.txt contains:

var nameField = this.getField('nameField');nameField.setAction('Keystroke', ...
var ageField = ...;function checkAge() {  if(event.value < 12) {...
var commentField = this.getField('commentField');commentField.setAction(...

You can reformat the file to make it easier to read. Added whitespaces do not affect a PDFUnit test.

Note

JavaScript is also used to implement the document actions OPEN, CLOSE, PRINT and SAVE. The discribed extraction utility does only extract JavaScript from document level, but no JavaScript that is bound to actions. A new utility is scheduled for the next release.