使用 iText 向 pdf 中的现有 acroform 字段添加 javascript 验证

Adding javascript validation to existing acroform field in pdf with iText

我正在尝试通过 java 中的 iText 将 java 脚本验证添加到现有的 Acroform 字段.到目前为止,我已经编写了以下代码,但没有为表单字段分配任何操作。有什么我想念的吗?

    PdfReader reader = new PdfReader(uri);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
    PdfWriter writer = stamper.getWriter();

    AcroFields acroFields = reader.getAcroFields();
    AcroFields.Item dateField = acroFields.getFieldItem("SignDateField");
    PdfAction pdfAction = PdfAction.javaScript("app.alert('hello');", writer);

    PdfDictionary widgetRefDict = (PdfDictionary) PdfReader.getPdfObject(dateField.getWidgetRef(0));
    PdfDictionary actionDict = widgetRefDict.getAsDict(PdfName.AA);
    if (actionDict == null) {
        actionDict = new PdfDictionary();
    }
    actionDict.put(PdfName.V, pdfAction);

    stamper.close();
    reader.close();

当注释词典中没有 AA 条目时,您正在创建一个新词典。但是您并没有将该新词典添加到注释词典中。

// ...
if (actionDict == null) {
    actionDict = new PdfDictionary();
    // add the newly created action dict
    widgetRefDict.put(PdfName.AA, actionDict);
}
// ...