Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a form field to an existing pdf with itextsharp?

Tags:

itextsharp

How to add a form field to an existing pdf with itextsharp?

I have an existing pdf document, I'd like to add form fields to it without creating a copy and writing out a new document.

like image 754
Tori Marrama Avatar asked Dec 04 '09 18:12

Tori Marrama


1 Answers

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();
}
like image 136
Tori Marrama Avatar answered Sep 20 '22 11:09

Tori Marrama