How to add an onMouseOver javaScript action to a TextField?

Tags: formstext fieldjavascript actionactionsiText 7

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;
// field.AddJavaScript = PdfAction.JavaScript(
// "this.getField(\"Total_0\").value = ( this.getField(\"Quantity_0\").value
// * this.getField(\"Price_0\").value ) / this.getField(\"Multiplier_0\").value;",
// writer);
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 iText 7 it will be done next way:

PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);
PdfFormField name = PdfFormField.createText(pdfDoc, new com.itextpdf.kernel.geom.Rectangle(130, 780, 126, 26)).
            setBorderColor(new DeviceGray(0.2f)).
            setAdditionalAction(PdfName.E, PdfAction.createJavaScript("app.alert('action!')"));

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. My snippet is written on Java, but you can easily do the same on C#.

Click this link if you want to see how to answer this question in iText 5.