|
<< Click to Display Table of Contents >> Navigation: Gnostice Document Studio .NET > Going Deeper > Document Engines > Working with PDF > Enhancement > Fill PDF form and flatten fields |
In this section we present example code to fill various types of form fields, and then flatten the form fields so that they can't be edited anymore. Before proceeding further please make sure that the prerequisite steps as listed in the Document Engines parent topic are followed.
Given below is the sample code. You can download the input PDF file that is used in the example from here.
string inputPDF = @"simpleForm_all_fields.pdf";
string outputPDF = @"pdf_filled_flattened.pdf";
using (var pdfDoc = new PDF())
{
pdfDoc.LoadDocument(inputPDF);
// Get the text field for "Given Name"
var fields = pdfDoc.GetAllFormFields(pageNo: 1, fieldName: "Text1");
var textField = fields[0] as PDFFormTextField;
textField.FieldValue = "John";
// Get the text field for "Family Name"
fields = pdfDoc.GetAllFormFields(pageNo: 1, fieldName: "Text8");
textField = fields[0] as PDFFormTextField;
textField.FieldValue = "Doe";
// Get the text field for "Address"
fields = pdfDoc.GetAllFormFields(pageNo: 1, fieldName: "Text2");
textField = fields[0] as PDFFormTextField;
textField.FieldValue = "123, Crippen Ct, Lakeland";
// Get the text field for "Date of Birth"
fields = pdfDoc.GetAllFormFields(pageNo: 1, fieldName: "Text6");
textField = fields[0] as PDFFormTextField;
textField.FieldValue = "01/01/1977";
// Get the checkbox for "English"
fields = pdfDoc.GetAllFormFields(pageNo: 1, fieldName: "Button2");
var checkboxField = fields[0] as PDFFormCheckBox;
checkboxField.Checked = true;
// Get the radiobutton for "Gender"
fields = pdfDoc.GetAllFormFields(pageNo: 1, fieldName: "Button1");
var radioField = fields[0] as PDFFormRadioButton;
radioField.SelectedItemIndex = 0; // Select first option (Male)
// Get the combobox for "Country of Residence"
fields = pdfDoc.GetAllFormFields(pageNo: 1, fieldName: "Choice1");
var comboField = fields[0] as PDFFormComboBox;
comboField.SelectedItemIndex = comboField.OptionList.IndexOf("United Kingdom");
// Get the listbox for "Favorite Color"
fields = pdfDoc.GetAllFormFields(pageNo: 1, fieldName: "Choice2");
var listField = fields[0] as PDFFormListBox;
listField.SelectedItemIndex = listField.OptionList.IndexOf("Red");
// Flatten the form fields so they can't be edited anymore
pdfDoc.ApplyFormAppearances = false;
pdfDoc.FlattenFormFields("1-", PDFAppearance.RecreateAlways);
// Save the modified document
pdfDoc.Save(outputPDF);
}