Created
March 17, 2026 17:37
-
-
Save aspose-com-kb/1eaecefcb5989d11610bc03c19ab49cb to your computer and use it in GitHub Desktop.
Add JavaScript to PDF using Java.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import com.aspose.pdf.Document; | |
| import com.aspose.pdf.JavascriptAction; | |
| public class AddJsToPdf | |
| { | |
| public static void main(String[] args) throws Exception | |
| { | |
| // Load Aspose license | |
| com.aspose.pdf.License license = new com.aspose.pdf.License(); | |
| license.setLicense("license.lic"); | |
| try | |
| { | |
| // Load an existing PDF | |
| Document document = new Document("input.pdf"); | |
| // Add JavaScript that runs when the PDF is opened | |
| JavascriptAction js = new JavascriptAction( | |
| "app.alert('Welcome! This PDF contains JavaScript.');" | |
| ); | |
| document.setOpenAction(js); | |
| // Add JavaScript that runs before the PDF is closed | |
| document.getActions().setBeforeClosing( | |
| new JavascriptAction( | |
| "app.alert('Thank you for viewing this PDF!');" | |
| // "app.launchURL(\"https://example.com\");" | |
| ) | |
| ); | |
| // Save the updated PDF | |
| document.save("output-with-javascript.pdf"); | |
| System.out.println("Done"); | |
| } | |
| catch (Exception e) | |
| { | |
| e.printStackTrace(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment