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 o
Using pdfStamper you can complete it.
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);
I struggled with this for awhile so figured I'd post the Question & Answer
Using the PdfStamper itext class is the key. (I guess this does make a copy but it's much cleaner than using the itext PdfCopy classes).
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();
}
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();
}