How to replace mergeField elements into doc in java using aspose.word

As i want to replace mergefield beside the fields so how i can do in java I need to programatically find all of these field which doesnt have mergefield so convert them to proper merge fields (e.g. «abc»).


i have attached input and target file for reference.

Hi Mahesh,


Thanks for your inquiry. First off, please visit the following article to learn about DOM structure of a document and how to move cursor to a particular position:

http://www.aspose.com/docs/display/wordsjava/Aspose.Words+Document+Object+Model
http://www.aspose.com/docs/display/wordsjava/Moving+the+Cursor

There are two ways you can use to insert merge field in document:

1) Using DocumentBuilder.InsertField method as follows:
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.insertField(" MERGEFIELD mf ");
doc.save(getMyDir() + “15.3.0.docx”);
2) Using DOM class FieldMergeField:
Document doc = new Document();
Paragraph para = doc.getFirstSection().getBody().getFirstParagraph();
FieldMergeField mergeField = (FieldMergeField)para.appendField(FieldType.FIELD_MERGE_FIELD, false);
mergeField.setFieldName(“mf”);
doc.save(getMyDir() + “15.3.0.docx”);
I hope, this helps.

Best regards,

Thanks Awais, but could you let me know how i can find those fields using aspose and please merged field next to it… please if possible can you provide code snippet and i had attached target file for reference.

Hi Mahesh,


Thanks for your inquiry. You can move cursor to individual cells and insert merge fields as follows:

Document doc = new Document(getMyDir() + “Input.docx”);
DocumentBuilder builder = new DocumentBuilder(doc);

builder.moveToCell(0, 1, 0, -1);
builder.insertField(" MERGEFIELD mf ");

doc.save(getMyDir() + “15.3.0.docx”);

Best regards,

Awais thanks for quick response, as that solution raise to another doubt if the document has table cell at different location then how we can figure it out the place to insert mergefield?


for example if the same cell is at the bottom of the page / or there is an another cell in the page then how this solution works?
Hi Mahesh,

Thanks for your inquiry. You can insert bookmarks in cells in input document and move cursor to bookmark using DocumentBuilder.MoveToBookmark method and insert merge field. Also, you can insert some special markers in input document and then use 'find and replace' functionality of Aspose.Words to replace those markers with merge fields. Please refer to the following articles:

http://www.aspose.com/docs/display/wordsjava/Find+and+Replace+Overview
http://www.aspose.com/docs/display/wordsjava/Aspose.Words+Document+Object+Model
http://www.aspose.com/docs/display/wordsjava/Moving+the+Cursor

I hope, this helps.

Best regards,