20

How do I insert JavaScript code into a PDF file?

I can code JavaScript, I just wish to know how to put it into a file to, for example, display the current date, use a combobox, etc.

2 Answers 2

16

JavaScript is typically tied to objects in a PDF document. For example, if you want the user to be able to print the PDF by clicking a Print button, follow the steps below:

  • Add a button to the form (done under advanced editing)
  • Right click on the button and go to properties
  • Click the actions tab
  • Under Select Action: choose Run a JavaScript
  • put print(); in the code window

Here's a link to an old (Acrobat 7.0.5) Acrobat JavaScript Scripting Reference to get you started.

Fresh Links 22/06/2020

Sign up to request clarification or add additional context in comments.

4 Comments

Dumb question: to follow these steps, what program would I be inside of?
@JasonSwett, Adobe Acrobat
This thread is a gold mine of information on a topic that has become of great interest to me.
is there a way to do this without doing per object programming. This feels like a terrible programming practice to add code to each object
6

You didn't stipulate a constraint for language, so you can use Python to achieve this. The library PyPDF2 [NOW pypdf] has a class called add_js that works. Here is an example from the REPL:

output.add_js("this.print({bUI:true,bSilent:false,bShrinkToFit:true});")
# Example: This will launch the print window when the PDF is opened.

and here is a link to the documentation. Note, that you need to have python3 installed (2.7 is going away at the end of 2019) and then run pip3 install pypdf or similar to install the library and then load it via import pypdf. Hopefully that helps.

2 Comments

Documentation for addJS says: "Deprecated since version 1.28.0." (see pypdf.readthedocs.io/en/stable/modules/…)
@Alex can you update my answer then? You can see I answered this in 2019...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.