简体   繁体   English

在 iText7 中专门为数字输入创建 PdfTextFormField

[英]Create PdfTextFormField in iText7 exclusively for numeric input

I need a PdfTextFormField that can carry only numeric input as decimal values (currency).我需要一个PdfTextFormField只能携带数字输入作为十进制值(货币)。 Other characters must be forbidden.必须禁止其他字符。 Any hints can also be given in Java although I code in C#.尽管我用 C# 编写代码,但也可以用 Java 给出任何提示。

Yes, it is possible.对的,这是可能的。 Actually Adobe has some functions that you can use for validation (watch AFNumber_ stuff on the code below):实际上,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();
}

This will create a form that will only take numbers, and you can use a "."这将创建一个只接受数字的表单,您可以使用“.”。 (period) for decimal places. (句点)表示小数位。

The PDF Reference mentions these Dictionary keys: 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.F - “在格式化字段以显示其当前值之前要执行的 JavaScript 操作。此操作可以在格式化之前修改字段的值。”
  • 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." PdfName.K - “当用户在文本字段或组合框中键入击键或修改可滚动列表框中的选择时要执行的 JavaScript 操作。此操作可以检查击键的有效性并拒绝或修改它。”

You can find some documentation on these functions on Adobe's Forms API Reference (page 119).您可以在Adobe 的 Forms API 参考(第 119 页)中找到有关这些功能的一些文档。

This mimics what you can set within Adobe Acrobat PRO:这模仿了您可以在 Adob​​e Acrobat PRO 中设置的内容:

Adobe Acrobat PRO 的屏幕截图

(I have tested this method in Adobe Reader and Foxit Reader. It is possible that some reader may not support it, in which case, I would recommend you implement your own Javascript validation in a similar fashion) (我已经在 Adob​​e Reader 和 Foxit Reader 中测试了这种方法。可能有些读者可能不支持它,在这种情况下,我建议您以类似的方式实现自己的 Javascript 验证)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM