代码之家  ›  专栏  ›  技术社区  ›  user2138736

ITextsharp c#字段计算

  •  0
  • user2138736  · 技术社区  · 12 年前

    有没有办法用iTextsharp创建自动计算字段?我尝试过用javascript来做这件事,但问题是字段值只在某些事件(例如mouseover、mouseup)期间更新。如果使用事件,则字段值仅在移动鼠标光标时更新。如果我在字段中写入一个值,然后将鼠标光标移动到其他位置,然后按enter键,它们就不会更新。当我将光标移回字段时,它们会得到更新。如果没有像“字段值更改”或类似的事件吗?

    1 回复  |  直到 12 年前
        1
  •  1
  •   Chris Haas    12 年前

    没有像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();
            }
        }
    }