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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With