【问题标题】:ITextsharp c# field calculationsITextsharp c# 字段计算
【发布时间】:2013-10-09 10:39:45
【问题描述】:

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

【问题讨论】:

    标签: c# javascript pdf itextsharp field


    【解决方案1】:

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

    在焦点事件中,我只是存储当前文本字段的值。在模糊事件中,我将存储值与新值进行比较,然后只是提醒它们是否相同或不同。如果您有一堆字段,您可能也希望使用全局数组而不是单个变量。有关详细信息,请参阅代码 cmets。这是针对 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();
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-17
      • 2012-10-11
      • 1970-01-01
      • 2016-09-28
      • 2011-03-28
      • 2015-02-07
      • 2020-07-09
      相关资源
      最近更新 更多