How do you add JavaScript to a PDF so that it executes when opening?
Estimated Reading Time: 1 MinutesTo add JavaScript to a PDF document, you need to set a PDF document's OpenAction to a JavaScript Action. The OpenAction value specifies a destination in the document that will be displayed when the document is opened, or an action that will be performed. If the OpenAction entry is blank, the PDF document will open at the top of the first page.
You can display and edit the OpenAction value for a PDF document when you open it in Adobe Acrobat.
You can then add JavaScript code directly to a PDF document using Adobe Acrobat, or you can generate the PDF using your own application, and add the JavaScript code to that PDF document programmatically.
To learn more see Section 12.6.4.16, “JavaScript Actions,” in the ISO 32000 Reference, Table 217, page 430.
Using the Java interface, the first step is to create a JavaScript action, as demonstrated by the following code snippet:
Action js_action = new Action(doc, "JavaScript"); String js_code = "app.alert(\"Welcome to my document.\");"; js_action.getPDFDict().put("JS", new PDFString(js_code,doc,false,false));
This adds the JavaScript code into a PDFString.
If you have a file of Javascript code, you will likely want to insert that code into a PDFStream:
PDFStream jsFileStmObj = new PDFStream(new FileInputStream(jsFileName), doc, new PDFDict(doc, false), new PDFArray(doc, false));
After that, to set the OpenAction in Java, you would call:
doc.getRoot().put("OpenAction", js_action.getPDFDict());
Using the .NET interface (C#), the corresponding code would be:
Action js_action = new Action(doc1, "JavaScript"); String js_code = "app.alert(\"Welcome to my document.\");"; js_action.PDFDict.Put("JS", new PDFString(js_code, doc1, false, false)); doc1.Root.Put("OpenAction", js_action.PDFDict);