questions.forms.AddActionToField.java Source code

Java tutorial

Introduction

Here is the source code for questions.forms.AddActionToField.java

Source

/*
 * This example was written by Bruno Lowagie, author of the book
 * 'iText in Action' by Manning Publications (ISBN: 1932394796).
 * You can use this example as inspiration for your own applications.
 * The following license applies:
 * http://www.1t3xt.com/about/copyright/index.php?page=MIT
 */

package questions.forms;

import java.io.FileOutputStream;
import java.io.IOException;

import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.PdfAction;
import com.lowagie.text.pdf.PdfDictionary;
import com.lowagie.text.pdf.PdfName;
import com.lowagie.text.pdf.PdfObject;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
import com.lowagie.text.pdf.AcroFields.Item;

public class AddActionToField {

    public static final String RESOURCE = "resources/questions/forms/hello_who.pdf";
    public static final String RESULT = "results/questions/forms/hello_action.pdf";

    public static void main(String[] args) {
        try {
            PdfReader reader = new PdfReader(RESOURCE);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
            AcroFields form = stamper.getAcroFields();
            Item fd = form.getFieldItem("Who");
            PdfDictionary dict = (PdfDictionary) PdfReader.getPdfObject((PdfObject) fd.getWidgetRef(0));
            PdfDictionary aa = dict.getAsDict(PdfName.AA);
            if (aa == null)
                aa = new PdfDictionary();
            aa.put(new PdfName("Fo"),
                    PdfAction.javaScript("app.alert('Who has got the focus!?');", stamper.getWriter()));
            dict.put(PdfName.AA, aa);
            stamper.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
}