How to Add Auto-Close JavaScript to PDF using C#

In this tutorial you’ll learn how to embed JavaScript into a PDF with C# so that the document automatically closes after a defined delay when opened in a compatible viewer such as Adobe Acrobat. This technique is ideal for time‑limited or temporary PDFs where automatic closure is required for security or workflow purposes. The solution hinges on setting the PDF’s OpenAction property to inject a JavaScript snippet that schedules the close operation.

Steps to Add Auto-Close JavaScript to PDF using C#

  1. Create a new C# console project and install the Aspose.PDF for .NET package via NuGet.
  2. Add necessary using directives: System.IO and Aspose.Pdf.
  3. Define input and output file paths and set the desired timeout in milliseconds before closing.
  4. Load the source PDF document using the Document class inside a using block for proper resource disposal.
  5. Construct a JavaScript string that uses app.setTimeOut to schedule document closure after the timeout.
  6. Assign the JavaScriptAction to the document’s OpenAction property to trigger the script on document open.
  7. Save the modified PDF to the output path using the Save method.

The steps above outline how to programmatically inject a JavaScript action that triggers automatically when the PDF is opened. The JavaScript uses the Acrobat JavaScript API’s app.setTimeOut method to delay execution of this.closeDoc() until the specified time has elapsed.

Code to Add Auto-Close JavaScript to PDF using C#

This example demonstrates how you can harness Aspose.PDF’s JavaScript capabilities to automatically trigger PDF actions upon opening, creating dynamic, time‑sensitive workflows that run without any user interaction.

 English