This article demonstrates how to fix invalid form fields in a Word document using GroupDocs.Editor for Python via .NET. It guides you through loading a document, identifying invalid form fields, and fixing them.
Step-by-Step Guide
Load the document into the Editor instance
Open the document as a binary stream and pass it to the Editor class together with WordProcessingLoadOptions. If the document is password-protected, specify the password through the load options.
fromgroupdocs.editorimportEditorfromgroupdocs.editor.optionsimportWordProcessingLoadOptionswithopen("form-fields.docx","rb")asstream:withEditor(stream,WordProcessingLoadOptions())aseditor:# Further code will be placed herepass
Check whether the document contains invalid form fields with has_invalid_form_fields(), and obtain their names with get_invalid_form_field_names().
has_invalid=field_manager.has_invalid_form_fields()print("FormFieldCollection contains invalid items:",has_invalid)invalid_names=list(field_manager.get_invalid_form_field_names())print("Invalid form field names:",invalid_names)
Fix the invalid form fields
The invalid form fields can be repaired with fix_invalid_form_field_names(...). The snippet below is illustrative — generate a unique replacement name for each invalid field and pass them to the method. Adjust the per-item access details to the exact members exposed by your build.
# Illustrative: assign unique fixed names and repair the invalid fieldsimportuuidinvalid_form_fields=field_manager.get_invalid_form_field_names()forinvalid_itemininvalid_form_fields:invalid_item.fixed_name="{0}_{1}".format(invalid_item.name,uuid.uuid4())field_manager.fix_invalid_form_field_names(invalid_form_fields)
Complete code example
Below is the complete runnable example. It opens the document, retrieves the form field manager, and reports whether it has invalid form fields together with their names. The repair steps shown above are illustrative; the runnable example performs only safe, documented calls.
importosfromgroupdocs.editorimportEditor,Licensefromgroupdocs.editor.optionsimportWordProcessingLoadOptionsdeffixing_invalid_form_fields():# Optionally set a licenselicense_path=os.path.abspath("./GroupDocs.Editor.lic")ifos.path.exists(license_path):License().set_license(license_path)# Open the document as a stream and load it with WordProcessingLoadOptionswithopen("./form-fields.docx","rb")asstream:withEditor(stream,WordProcessingLoadOptions())aseditor:# Read the FormFieldManager instancefield_manager=editor.form_field_manager# Detect invalid form fieldsprint("Has invalid form fields:",field_manager.has_invalid_form_fields())invalid_form_fields=list(field_manager.get_invalid_form_field_names())print("Invalid form fields detected:",len(invalid_form_fields))if__name__=="__main__":fixing_invalid_form_fields()
form-fields.docx is the sample file used in this example. Click here to download it.
Has invalid form fields: True
Invalid form fields detected: 21