@alexey.noskov in attached document, we read the fields to replace the bookmarks and merged fields with correct value, at the beginning number of fields are 161 but after running the code the number increased to 166. I figured out calling updateFields() triggers this issue.
GEN152MNotestoestimatedoutcomestatement.docx (37.2 KB)
/**@type {plugins.file.JSFile}*/
var wordDoc = wordDocuments[index];
scopes.ipsLog.debug('wordDoc path: ' + wordDoc.getPath());
var docOrg = new Document(wordDoc.getPath(), options);
var builder = new DocumentBuilder(docOrg);
//get list of fields
var fields = docOrg.getRange().getFields();
// check if there is any fill-in fields, remove them and insert MergeFields
var startsNode = docOrg.getChildNodes(NodeType.FIELD_START, true).toArray();
var bms = docOrg.getRange().getBookmarks();
for (var f = 0; f < fields.getCount(); f++)
{
var field = fields.get(f);
application.output("****************** field name is : " + field.getFieldCode() + " and type is: " + field.getType() + " and index is " + f);
if (field.getStart().getFieldType() == FieldType.FIELD_ASK)
{
/**@type {Packages.com.aspose.words.FieldAsk}*/
var ask = field;
var bookmarkname = ask.getBookmarkName();
for (var b = 0; b < bookmarks.length; b++)
{
var bVal = bookmarks[b];
/**@type {String}*/
var bKey = bVal.key;
var vValKey = '';
if (bKey)
{
var bVals = bKey.split("_");
if (bVals.length > 0)
{
vValKey = bVals[0];
}
}
if (bookmarkname == vValKey)
{
/**@type {Packages.com.aspose.words.Bookmark}*/
var askBookmark = bms.get(vValKey);
var newbookmark = null;
if (askBookmark)
{
//remove bookmard and add it back in order to be set in correct place in the file
askBookmark.remove();
ask.setResult('');
builder.moveTo(ask.getEnd());
builder.startBookmark(vValKey);
builder.endBookmark(vValKey);
if (bVal.value)
{
newbookmark = docOrg.getRange().getBookmarks().get(vValKey);
newbookmark.setText(bVal.value);
}
break;
}
else
{
//if there is no bookmark in the document, add it
ask.setResult('');
builder.moveTo(ask.getEnd());
builder.startBookmark(vValKey);
builder.endBookmark(vValKey);
if (bVal.value)
{
newbookmark = docOrg.getRange().getBookmarks().get(vValKey);
// newbookmark.setText(bVal.value);
docOrg.getRange().getBookmarks().get(vValKey).setText(bVal.value);
}
break;
}
}
}
docOrg.updateFields();
}
else if (field.getStart().getFieldType() == FieldType.FIELD_FILL_IN)
{
var name = "Q_" + f
builder.moveToField(field, true);
builder.insertField("MERGEFIELD " + name);
field.remove();
docOrg.updateFields();
}
var filePathNew = FILE_DOWLOAD_PATH + "file_" + application.getUUID() + '.docx';
//save the document and use this file for the process
docOrg.save(filePathNew);