Legacy notice!

iText 5 is the previous major version of iText's leading PDF SDK. iText 5 has been EOL, and is no longer developed. Switch your project to iText 7, integrating the latest developments.
Check related iText 7 content!

How can I add javascripts to iTextsharp created textfields?

How can I add javascripts to iTextsharp created textfields? I've tried following:

TextField field = new iTextSharp.text.pdf.TextField(writer,
    new iTextSharp.text.Rectangle(x, y - h, x + w, y), name);
field.BackgroundColor =
    new BaseColor(bgcolor[0], bgcolor[1], bgcolor[2]);
field.BorderColor =
    new BaseColor(bordercolor[0], bordercolor[1], bordercolor[2]);
field.BorderWidth = border;
field.BorderStyle = PdfBorderDictionary.STYLE_SOLID;
field.Text = text;
// PROBLEM:
// field.AddJavaScript = PdfAction.JavaScript(
// "this.getField(\"Total_0\"").value = ( this.getField(\""Quantity_0\"").value

The problem is: iTextSharp.text.pdf.TextField does not contain a definition for AddJavaScript. So then how can I add javascript that activates when mouse cursor is over text field or when text field has been edited? My purpose is to calculate value from other text fields to this one with Javascript.

Posted on StackOverflow on Sep 20, 2013 by mikessu


What you're looking for is called an additional action. For instance: you have an entry action, defined using PdfName.E and an exit action, defined by PdfName.X. The entry action is triggered when the mouse enters the rectangle that defines the field; the exit action is triggered when the mouse exist the rectangle that defines the field.

In your code, you're skipping a step and that's probably why you didn't find the function you need:

PdfFormField ffield = field.GetTextField();
ffield.SetAdditionalActions(PdfName.E, PdfAction("app.alert('action!')"));
writer.AddAnnotation(ffield);

This snippet will cause an alert to appear when the mouse enters the text field. Other options are PdfName.D (mouseDown), PdfName.U (mouseUp), PdfName.K (keystroke by user), PdfName.V (validate, because the value of the field has changed), etc.