Form field has been widely used by developers to display, catch and edit data. Developers may create a form to let others to fill the data and then save the form as a non-fillable file and set it to read only. Spire.PDF supports to create and fill form field; this article will focus on show you how to change the field's value and set all the fields on a form to read only.
By using the PdfFormWidget class, we can get the PDF field collection on the form and then update the values on it. Here comes to the code snippet of how to change the form field's value and set it to read only:
Step 1: Create PDFDocument and load from file.
PdfDocument doc = new PdfDocument(); doc.LoadFromFile("FormField.pdf");
Step 2: Get the PDF field collection on the Form.
PdfFormWidget widget = doc.Form as PdfFormWidget;
Step 3: Traverse each PDF field in pdf field collection.
for (int i = 0; i < widget.FieldsWidget.List.Count; i++) { PdfField f = widget.FieldsWidget.List[i] as PdfField;
Step 4: Find a PDF field named username and set the value for it.
if (f.Name == "username") { //Convert the pdf field to PdfTextBoxFieldWidget PdfTextBoxFieldWidget textboxField = f as PdfTextBoxFieldWidget; //Change its text textboxField.Text = "Sky.Luo"; }
Step 5: Set the field to read-only.
f.Flatten = true; f.ReadOnly = true;
Step 6: Save the document to file and launch to view it.
doc.SaveToFile("FormFieldEdit.pdf"); System.Diagnostics.Process.Start("FormFieldEdit.pdf");
Effective screenshot of the read only form field:
Full codes:
using Spire.Pdf; using Spire.Pdf.Fields; using Spire.Pdf.Widget; namespace ReadOnlyField { class Program { static void Main(string []args) { PdfDocument doc = new PdfDocument(); doc.LoadFromFile("FormField.pdf"); PdfFormWidget widget = doc.Form as PdfFormWidget; for (int i = 0; i < widget.FieldsWidget.List.Count; i++) { PdfField f = widget.FieldsWidget.List[i] as PdfField; if (f.Name == "username") { PdfTextBoxFieldWidget textboxField = f as PdfTextBoxFieldWidget; textboxField.Text = "Sky.Luo"; } f.Flatten = true; f.ReadOnly = true; } doc.SaveToFile("FormFieldEdit.pdf"); System.Diagnostics.Process.Start("FormFieldEdit.pdf"); } } }