How to create pdfformfields using iTextSharp?

匆匆过客 提交于 2019-11-29 16:36:05

You're creating a field 'the hard way'. There's a class named RadioCheckField that makes it much easier for you to create a field.

Please take a look at the book examples from Chapter 8. You can find C# versions of the examples here, for instance an example named Buttons.

checkbox = new RadioCheckField(writer, rect, LANGUAGES[i], "on");
checkbox.CheckType = RadioCheckField.TYPE_CHECK;
PdfFormField field = checkbox.CheckField;

You can create your custom form template using LiveCycle and then data bind the form fields using iTextSharp like this

string randomFileName = Helpers.GetRandomFileName();
string formTemplate = Server.MapPath("~/FormTemplate.pdf");
 string formOutput = Server.MapPath(string.Format("~/downloads/Forms/Form-{0}.pdf",    randomFileName));

PdfReader reader = new PdfReader(formTemplate);
PdfStamper stamper = new PdfStamper(reader, new System.IO.FileStream(formOutput,   System.IO.FileMode.Create));
AcroFields fields = stamper.AcroFields;

// set form fields
fields.SetField("Date", DateTime.Now.ToShortDateString());
fields.SetField("FirstName", user.FirstName);
fields.SetField("LastName", user.LastName);
fields.SetField("Address1", user.Address1);
fields.SetField("Address2", user.Address2);
fields.SetField("City", user.City);
fields.SetField("State", user.State);
fields.SetField("Zip", user.Zip);
fields.SetField("Email", user.Email);
fields.SetField("Phone", user.Phone);

// set document info
System.Collections.Hashtable info = new System.Collections.Hashtable();
info["Title"] = "User Information Form";
info["Author"] = "My Client";
info["Creator"] = "My Company";
stamper.MoreInfo = info;

 // flatten form fields and close document
stamper.FormFlattening = true;
stamper.Close();

You do not need to use a PdfStamper to create AcroForm form fields in a PDF, PdfWriter also allows you to.

Unfortunately you neither said in which way your code didn't work nor what exact requirements you have; still some sample code might bring you on track:

Have a look at chapter 8 of iText in Action, 2nd edition; especially the sample Buttons will give you numerous hints on how to create radio buttons and check boxes. The sample ChoiceFields will show you how to create list and combo boxes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!