@kerner Please try using the following code to achieve what you need.
Document doc = new Document("C:\\Temp\\in.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
// Loop through form fields in the document.
for (FormField ff : doc.getRange().getFormFields())
{
if (ff.getType() == FieldType.FIELD_FORM_TEXT_INPUT)
{
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PLAIN_TEXT, MarkupLevel.INLINE);
sdt.isShowingPlaceholderText(true);
sdt.setAppearance(SdtAppearance.BOUNDING_BOX);
sdt.setTitle(ff.getName());
builder.moveToBookmark(ff.getName(), false, true);
builder.insertNode(sdt);
}
}
// Loop through fields in the document and remove text fields.
for (Field f : doc.getRange().getFields())
{
if (f.getType() == FieldType.FIELD_FORM_TEXT_INPUT)
f.remove();
}
doc.save("C:\\Temp\\out.docx");
If the problem still persist, please attach your input and output documents here for our reference.
@kerner Could you please attach the problematic document here for testing? We will check the issue and provide you more information. Normally, form field is associated with bookmark in the document and the appropriate field.
@kerner Thank you for additional information. You are right there is a buggy form field without a bookmark in your document. You can try using the following code:
Document doc = new Document("C:\\Temp\\in.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
// Loop through fields in the document and replace text fields with SDT.
for (Field f : doc.getRange().getFields())
{
if (f.getType() == FieldType.FIELD_FORM_TEXT_INPUT)
{
// Get Form field wrapped with the field.
FormField ff = null;
Node currentNode = f.getStart();
while (currentNode != null && currentNode != f.getEnd())
{
if (currentNode.getNodeType() == NodeType.FORM_FIELD)
{
ff = (FormField)currentNode;
break;
}
currentNode = currentNode.getNextSibling();
}
// put SDT after the field.
if (ff != null)
{
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PLAIN_TEXT, MarkupLevel.INLINE);
sdt.isShowingPlaceholderText(true);
sdt.setAppearance(SdtAppearance.BOUNDING_BOX);
sdt.setTitle(ff.getName());
builder.moveToField(f, true);
builder.insertNode(sdt);
}
f.remove();
}
}
doc.save("C:\\Temp\\out.docx");