0

有没有办法使用 iTextsharp 创建自动计算字段?我曾尝试使用 javascript 执行此操作,但问题是字段值仅在某些事件期间更新(例如 mouseover、mouseup)。如果我使用事件,则字段值仅在我移动鼠标光标时更新。如果我将值写入字段,然后将鼠标光标移动到其他位置,然后按 Enter,它们不会得到更新。当我将光标移回该字段时,它们会更新。Afaik 没有像“字段值更改”或类似的事件吗?

4

1 回答 1

1

没有像 HTML 那样的“on changed”事件,但是有“on focus”和“on blur”事件,所以你可以很容易地编写自己的事件。下面的代码显示了这一点。它首先创建一个全局 JavaScript 变量(这不是必需的,您可以丢弃该行,它只是帮助我思考)。然后它创建一个标准文本字段并设置两个动作,Fo(焦点)事件和Bl(模糊)事件。您可以在 PDF 标准第 12.6.3 节表 194 中找到这些事件和其他事件。

在焦点事件中,我只是存储当前文本字段的值。在模糊事件中,我将存储值与新值进行比较,然后只是提醒它们是否相同或不同。如果您有一堆字段,您可能也希望使用全局数组而不是单个变量。有关更多信息,请参阅代码注释。这是针对 iTextSharp 5.4.2.0 测试的。

//Our test file
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf");

//Standard PDF creation, nothing special
using (var fs = new FileStream(testFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
    using (var doc = new Document()) {
        using (var writer = PdfWriter.GetInstance(doc, fs)) {
            doc.Open();

            //Add a global variable. This line is 100% not needed but it helps me think more clearly
            writer.AddJavaScript(PdfAction.JavaScript("var first_name = '';", writer));

            //Create a text field
            var tf = new TextField(writer, new iTextSharp.text.Rectangle(50, 50, 300, 100), "first_name");
            //Give it some style and default text
            tf.BorderStyle = PdfBorderDictionary.STYLE_INSET;
            tf.BorderColor = BaseColor.BLACK;
            tf.Text = "First Name";

            //Get the underlying form field object
            var tfa = tf.GetTextField();

            //On focus (Fo) store the value in our global variable
            tfa.SetAdditionalActions(PdfName.FO, PdfAction.JavaScript("first_name = this.getField('first_name').value;", writer));

            //On blur (Bl) compare the old value with the entered value and do something if they are the same/different
            tfa.SetAdditionalActions(PdfName.BL, PdfAction.JavaScript("var old_value = first_name; var new_value = this.getField('first_name').value; if(old_value != new_value){app.alert('Different');}else{app.alert('Same');}", writer));

            //Add our form field to the document
            writer.AddAnnotation(tfa);

            doc.Close();
        }
    }
}
于 2013-10-09T14:06:15.933 回答