Add JavaScript to PDFs with TX Text Control in C# .NET: Time-Based Alerts Made Easy
In this article, we explore how to enrich PDF documents with JavaScript using TX Text Control in C# .NET. Read on to learn how to create time-based alerts that trigger actions based on specific conditions, making your PDFs interactive and dynamic.

A PDF is more than just a static page layout format; it's also a dynamic platform that can run JavaScript. This may surprise some developers, but JavaScript in PDFs is a powerful and standardized feature supported by most desktop viewers, such as Adobe Acrobat.
In this article, we will explore a practical use case for time-based document behavior using JavaScript. You will learn when and why this behavior is helpful and how to implement it using TX Text Control in .NET applications.
Why Use JavaScript in PDF Documents?
You can use embedded JavaScript in PDFs to make documents interactive, secure, or user-aware. Common use cases include:
- Form validation before submission to ensure that all required fields are filled out correctly.
- Automatic field calculations to compute totals or other values based on user input.
- Dynamic content updates that change based on user actions or specific conditions.
- Expiration notices that alert users when a document is no longer valid or needs attention.
Although the JavaScript environment in PDF viewers is more limited than in web browsers, it enables meaningful interactivity when combined with forms or logic that runs when the document opens.
Implementing Time-Based Alerts
Now, let's focus on a particularly useful scenario: Document expiration messages.
Imagine generating documents for limited-time offers, such as forms for a specific year or compliance-related disclosures. You want to notify users who open the document after a certain date and instruct them to either contact support or access a newer version.
The following dialog alert is displayed when the document is opened in Acrobat Reader after its expiration. Let's take a look at it.
With TX Text Control, it's easy to embed JavaScript into your PDFs, including actions that are triggered when the document is opened.
using TXTextControl.ServerTextControl serverTextControl = new TXTextControl.ServerTextControl();
serverTextControl.Create();
serverTextControl.Text = "I am a PDF document that expires May 1, 2025!\fPage2\fPage3\fPage4\fPage5";
var jsCode = @"
var expirationDate = new Date('2025-05-01T00:00:00');
var now = new Date();
if (now > expirationDate) {
app.alert({
cMsg: '⚠️ This document has expired.\n\n📞 Please contact: support@example.com\n🕒 Validity ended on May 1, 2025.',
cTitle: 'Document Expired',
nIcon: 1,
nType: 0
});
}
";
TXTextControl.SaveSettings saveSettings = new TXTextControl.SaveSettings()
{
DocumentLevelJavaScriptActions = new string[] { jsCode }
};
serverTextControl.Save("output.pdf", TXTextControl.StreamType.AdobePDF, saveSettings);
This script checks the current date and displays a warning if the document has expired. The app.alert dialog box supports line breaks, icons, and basic formatting, such as emojis. Keep in mind that overly complex or malicious scripts may trigger warnings or be blocked by viewer security settings.
Adding Visual Annotations
Although the JavaScript alert is effective, it may not be immediately visible to users. To make the expiration notice more prominent, add a visual annotation to the PDF document. This could be a simple text box or a more complex graphic highlighting the expiration date.
You can use the this.addAnnot method to create this annotation using JavaScript. Here's an example of how to add a rectangle containing a message:
using TXTextControl.ServerTextControl serverTextControl = new TXTextControl.ServerTextControl();
serverTextControl.Create();
serverTextControl.Text = "I am a PDF document that expires May 1, 2025!\fPage2\fPage3\fPage4\fPage5";
var jsCode = @"
var expirationDate = new Date('2025-05-01T00:00:00');
var now = new Date();
if (now > expirationDate) {
var page = this.getPageNumWords(0) > 0 ? 0 : this.pageNum;
this.addAnnot({
page: 0,
type: 'FreeText',
rect: [100, 600, 400, 650],
contents: 'EXPIRED',
name: 'expiredLabel',
author: 'System',
subject: 'Expiration Warning',
strokeColor: color.blue,
fillColor: color.transparent
});
}
";
TXTextControl.SaveSettings saveSettings = new TXTextControl.SaveSettings
{
DocumentLevelJavaScriptActions = new string[] { jsCode }
};
serverTextControl.Save("output.pdf", TXTextControl.StreamType.AdobePDF, saveSettings);
You can also use a button or link in the annotation to direct users to a support page or a newer version of the document. This improves usability and ensures users are aware of the document's status. The following example shows how to create a button that opens a URL when clicked.
Here's how to create a button that opens a URL when it is clicked:
using TXTextControl.ServerTextControl serverTextControl = new TXTextControl.ServerTextControl();
serverTextControl.Create();
serverTextControl.Text = "I am a PDF document that expires May 1, 2025!\fPage2\fPage3\fPage4\fPage5";
var jsCode = @"
var expirationDate = new Date('2025-05-01T00:00:00');
var now = new Date();
if (now > expirationDate) {
var page = this.getPageNumWords(0) > 0 ? 0 : this.pageNum;
// Add a visible button to open a website
this.addField('visitSiteButton', 'button', 0, [100, 500, 400, 530]);
var f = this.getField('visitSiteButton');
// Set the caption text
f.buttonSetCaption('Document expired! Click to download latest version.');
// Make it visually look like a button
f.textFont = font.Helv; // Helvetica font
f.textSize = 12;
f.textColor = color.white;
f.fillColor = color.red;
f.strokeColor = color.red;
f.borderStyle = border.b; // Solid border
f.lineWidth = 2;
// Set the action to open the URL on click
f.setAction('MouseUp', 'app.launchURL(""https://www.textcontrol.com"", true);');
}
";
TXTextControl.SaveSettings saveSettings = new TXTextControl.SaveSettings
{
DocumentLevelJavaScriptActions = new string[] { jsCode }
};
serverTextControl.Save("output.pdf", TXTextControl.StreamType.AdobePDF, saveSettings);
Conclusion
JavaScript in PDF documents is a powerful tool that can improve the user experience by providing dynamic, critical information. Implementing time-based alerts and visual annotations ensures that users are aware of important document statuses, such as expiration dates.
TX Text Control simplifies the integration of JavaScript into your PDF workflows, enabling you to create interactive, user-friendly documents. Consider how JavaScript can add value and improve usability when building forms, reports, or any other type of document.
ASP.NET
Integrate document processing into your applications to create documents such as PDFs and MS Word documents, including client-side document editing, viewing, and electronic signatures.
- Angular
- Blazor
- React
- JavaScript
- ASP.NET MVC, ASP.NET Core, and WebForms
Related Posts
Mining PDFs with Regex in C#: Practical Patterns, Tips, and Ideas
Mining PDFs with Regex in C# can be a powerful technique for extracting information from documents. This article explores practical patterns, tips, and ideas for effectively using regular…
Streamline Data Collection with Embedded Forms in C# .NET
Discover how to enhance your C# .NET applications by embedding forms for data collection. This article explores the benefits of using Text Control's ASP.NET and ASP.NET Core components to create…
Adding QR Codes to PDF Documents in C# .NET
This article explains how to add QR codes to PDF documents with the Text Control .NET Server component in C#. It provides the necessary steps and code snippets for effectively implementing this…
Adding SVG Graphics to PDF Documents in C# .NET
In this article, we will explore how to add SVG graphics to PDF documents using C# .NET. We will use the TX Text Control .NET Server component to demonstrate the process of rendering SVG images in…
Enhancing PDF Searchability in Large Repositories by Adding and Reading…
This article explores how to improve the searchability of PDF documents in large repositories by adding and reading keywords with C# .NET. This is especially helpful for applications that manage…