在 iText7 中创建专门用于数字输入的 PdfTextFormField

Create PdfTextFormField in iText7 exclusively for numeric input

我需要一个 PdfTextFormField,它只能将数字输入作为十进制值(货币)。必须禁止使用其他字符。尽管我用 C# 编写代码,但也可以在 Java 中给出任何提示。

是的,这是可能的。实际上,Adobe 有一些功能可用于验证(观看下面代码中的 AFNumber_):

public void helloWorldForm() throws IOException {
    logger.info("create PDF on {}", DEST);

    final PdfWriter pdfWriter = new PdfWriter(DEST);
    final PdfDocument pdfDocument = new PdfDocument(pdfWriter);

    try (final Document document = new Document(pdfDocument)) {

        document.add(new Paragraph("Number with 2 decimal places"));

        PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDocument, true);
        PdfTextFormField nameField = PdfTextFormField.createText(pdfDocument,
                new Rectangle(99, 753, 425, 15), "value", "");
        form.addField(nameField);

        PdfAction validation = PdfAction.createJavaScript("AFNumber_Format(2,0,0,0,\"\", true);");
        nameField.setAdditionalAction(PdfName.F, validation);

        validation = PdfAction.createJavaScript("AFNumber_Keystroke(2,0,0,0,\"\", true);");
        nameField.setAdditionalAction(PdfName.K, validation);

    }

    pdfDocument.close();
}

这将创建一个只接受数字的表单,您可以使用“.”。 (句点)用于小数位。

PDF 参考中提到了这些字典键:

  • PdfName.F - "A JavaScript action to be performed before the field is formatted to display its current value. This action can modify the field’s value before formatting."
  • PdfName.K - "A JavaScript action to be performed when the user types a keystroke into a text field or combo box or modifies the selection in a scrollable list box. This action can check the keystroke for validity and reject or modify it."

您可以在 Adobe's Forms API Reference(第 119 页)上找到有关这些 函数 的一些文档。

这模拟了您可以在 Adob​​e Acrobat PRO 中设置的内容:

(我在AdobeReader和FoxitReader测试过这个方法,有可能有些reader不支持,这种情况下,我建议你实现您自己的 Javascript 以类似方式验证)