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

Tor*_*ama 12 itextsharp

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

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

Tor*_*ama 7

经过进一步审查,该领域的裁决被推翻.如果你将压模压平,那么结果文件中没有显示字段(因为它们缺少"外观"设置).顺便说一句,表单展平会阻止表单字段的进一步编辑.现在我们可以为表单添加外观,但是,更简单的方法是使用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();
}
Run Code Online (Sandbox Code Playgroud)

  • 添加了AddAnotation的字段无论如何都没有展平,请参阅itextsharp源代码中关于Formflattening属性的注释http://sourceforge.net/p/itextsharp/code/453/tree/trunk/src/core/iTextSharp/text/ PDF/PdfStamper.cs (2认同)