且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用itextsharp将表单字段添加到现有pdf?

更新时间:2023-02-12 21:14:55

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

After further review, the ruling on the field is overturned. Turns out if you form flatten the stamper the fields do not show on the resulting document (because they lack 'appearance' settings). BTW, form flattening prevents further edits of a form field. Now we can add appearance to the form, however, an easier way is to use the TextField class and not worry about explicitly setting up 'appearance' objects.

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