Debenu Quick PDF Library enables you to programmatically flatten PDF form fields.

Flattening a PDF form means that the content (text and images) of the form fields are converted to regular text and image objects in the PDF and the form fields are removed.

The FormFieldCount function always returns the total number form fields in the document at the time the function is called. When FlattenFormField succeeds (returns 1) the field will be deleted from the PDF. This means that the field index of subsequent form fields will be reduced by 1. So the correct way to flatten the form fields is to keep a variable which is the current form field number and only increase it if the flattening fails.

Something like this:

// Count the total number of form fields in the file
 
DPL.LoadFromFile("FileName.pdf", "");
 
TotalFormFields = DPL.FormFieldCount();
 
// Loop through each of the form fields and
// flatten them using the FlattenFormField function
 
while (TotalFormFields > 0)
{
  DPL.FlattenFormField(TotalFormFields);
  TotalFormfields = TotalFormFields--;
}
DPL.SaveToFile("FileName_Updated.pdf");

DPL.LoadFromFile("FileName.pdf", "");

TotalFormFields = DPL.FormFieldCount();

// Loop through each of the form fields and
// flatten them using the FlattenFormField function

while (TotalFormFields > 0)
{
  DPL.FlattenFormField(TotalFormFields);
  TotalFormfields = TotalFormFields--;
}
DPL.SaveToFile("FileName_Updated.pdf");

Alternatively, if your PDF form fields do not include appearance streams then it is necessary to generate them prior to flattening the form fields. This can be achieved using the UpdateAndFlattenFormField function which will draw the visual appearance of the form field onto the page it is associated with it. The form field will then be removed from the document and only its appearance stream will remain. If you are unsure about the presence of appearance streams then using this function is the safer option.

The same code as above can be used by replace FlattenFormField with UpdateAndFlattenFormField.

// Count the total number of form fields in the file
 
DPL.LoadFromFile("FileName.pdf", "");
 
TotalFormFields = DPL.FormFieldCount();
 
// Loop through each of the form fields and
// flatten them using the FlattenFormField function
 
while (TotalFormFields > 0)
{
  DPL.UpdateAndFlattenFormField(TotalFormFields);
  TotalFormfields = TotalFormFields--;
}
DPL.SaveToFile("FileName_Updated.pdf");

DPL.LoadFromFile("FileName.pdf", "");

TotalFormFields = DPL.FormFieldCount();

// Loop through each of the form fields and
// flatten them using the FlattenFormField function

while (TotalFormFields > 0)
{
  DPL.UpdateAndFlattenFormField(TotalFormFields);
  TotalFormfields = TotalFormFields--;
}
DPL.SaveToFile("FileName_Updated.pdf");

If you want to update the appearance stream of form fields independently of flattening the form fields then read this article on appearance streams in PDF forms.