【问题标题】:How to add a form field to an existing pdf with itextsharp?如何使用 itextsharp 向现有 pdf 添加表单域?
【发布时间】:2009-12-04 18:50:28
【问题描述】:

如何使用 itextsharp 向现有 pdf 添加表单域?

我有一个现有的 pdf 文档,我想在不创建副本和写出新文档的情况下向其中添加表单域。

【问题讨论】:

    标签: itextsharp


    【解决方案1】:

    经过进一步审查,该领域的裁决被推翻。事实证明,如果您将压模压平,则字段不会显示在结果文档上(因为它们缺少“外观”设置)。顺便说一句,表单展平可防止进一步编辑表单字段。现在我们可以为表单添加外观,但是,更简单的方法是使用 TextField 类,而不必担心显式设置“外观”对象。

    public void ABetterWayToAddFormFieldToExistingPDF( )
    {
        PdfReader reader = new PdfReader(@"c:\existing.pdf");
    
        FileStream out = new FileStream(@"C:\existingPlusFields.pdf", FileMode.Create, FileAccess.Write);
    
        PdfStamper stamp = new PdfStamper(reader, out);           
    
        TextField field = new TextField(stamp.Writer, new iTextSharp.text.Rectangle(40, 500, 360, 530), "some_text");
    
       // add the field here, the second param is the page you want it on         
        stamp.AddAnnotation(field.GetTextField(), 1);
    
        stamp.FormFlattening = true; // lock fields and prevent further edits.
    
        stamp.Close();
    }
    

    【讨论】:

    【解决方案2】:

    我为此苦苦挣扎了一段时间,所以想发布问题和答案

    使用 PdfStamper itext 类是关键。 (我想这确实会复制,但它比使用 itext PdfCopy 类要干净得多)。

    public void AddFormFieldToExistingPDF( )
    {
        PdfReader reader = new PdfReader(@"c:\existing.pdf");
    
        FileStream out = new FileStream(@"C:\existingPlusFields.pdf", FileMode.Create, FileAccess.Write);
    
        PdfStamper stamp = new PdfStamper(reader, out);           
    
        PdfFormField field = PdfFormField.CreateTextField(stamp.Writer, false, false, 50);
    
        // set a field w/some position and size
        field.SetWidget(new iTextSharp.text.Rectangle(40, 500, 360, 530),
                PdfAnnotation.HIGHLIGHT_INVERT);
    
        field.SetFieldFlags(PdfAnnotation.FLAGS_PRINT);
        field.FieldName = "some_field";
    
        // add the field here, the second param is the page you want it on
        stamp.AddAnnotation(field, 1);                        
        stamp.Close();
    }
    

    【讨论】:

    • 我的代码和你的很相似。签名字段在屏幕上的行为完全正常,但是一旦我尝试打印它,它在纸上显示为空白。你会遇到这种情况吗?
    【解决方案3】:

    使用pdfStamper即可完成。

    PdfStamper Stamper= new PdfStamper(new PdfReader(sourcefile), File.Create(NewOutputFile)); 
    
    TextField moreText = new TextField(Stamper.Writer,
                              new iTextSharp.text.Rectangle(20, 20, 590, 780), "moreText");
    
                moreText.Visibility = TextField.VISIBLE_BUT_DOES_NOT_PRINT;
                moreText.Text = "Use this space for any additional information";
                moreText.Options = (TextField.MULTILINE);
    
    PdfFormField Fieldtxt = moreText.GetTextField();
    
    Stamper.AddAnnotation(Fieldtxt, n);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-12
      • 2013-02-09
      • 1970-01-01
      • 1970-01-01
      • 2015-06-23
      • 2013-02-10
      • 1970-01-01
      相关资源
      最近更新 更多