This article explains how to add JavaScript to PDF using Python. It will share details to set the environment for the development, a list of steps, and a sample code for creating a PDF with JS using Python. You will learn various methods to add JavaScript to different actions for a PDF.
Steps to Add PDF JS using Python
- Set the environment to use Aspose.PDF for Python via .NET to add JS to PDF
- Import Document, License, and JavascriptAction classes from the library
- Load the existing PDF into the Document class object
- Create JavaScript that will execute when the PDF file opens
- Set this JavaScript to the Open action using the Document.open_action property
- Access the collection of actions and add another script to the before closing action
- Save the PDF file with JavaScript in it
The above steps summarize how to add JavaScript inside PDF using Python. Import the desired classes Document, License, and JavascriptAction from the library, load the existing PDF file into the Document class object, create a JavascriptAction with an appropriate message, and set it to the open action in the PDF. To assign JS to other actions in the PDF, access the collection of actions in the PDF, create a new JavaScriptAction object with another message, and set it to another event, such as before_closing. Then, save the output PDF.
Code for PDF Scripting using Python
The above code demonstrates the process of adding JavaScript in PDF files using Python. You can handle other actions such as BeforeSaving, BeforeClosing, AfterSaving, BeforePrinting, and AfterPrinting. The JavascriptAction class supports setting various actions like opening a URL using the app.launchURL method.
This article has taught us the process to add JavaScript to a PDF file. To add a tooltip to a PDF file, refer to the article Remove Highlight from PDF using Python.