We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Changing mergefields by insertHtml without changing the format

Good morning,

i’m using aspose word for java v11; MS word 2010 and I want to change an existing mergefield in a word document by HTML value without changing the mergefield format, the problem is when I use this source code:

builder.moveToMergeField(“test”);
builder.insertHtml(“Hello”);

the text “Hello” doesn’t take the mergefield format ( font name, font size, color, italic, bold, …)

any help please ?


best regards

Hi Yasser,


Thanks for your inquiry. Please note that, content inserted by DocumentBuilder.insertHtml method does not inherit formatting specified in DocumentBuilder options. Whole formatting is taken from HTML snippet. If you insert HTML with no formatting specified, then default formatting is used for inserted content, e.g. if font is not specified in your HTML snippet, default font will be applied (Times New Roman).

In your case, I suggest you to use INodeChangingCallback interface to achieve your requirements. Please check following documentation link.
http://www.aspose.com/docs/display/wordsjava/INodeChangingCallback

Please use the following code snippet for your requirement.

<span lang=“EN-GB” style=“font-size:10.0pt;font-family:“Courier New”;color:blue;mso-font-kerning:
0pt;mso-no-proof:yes”>public<span lang=“EN-GB” style=“font-size:10.0pt;
font-family:“Courier New”;mso-font-kerning:0pt;mso-no-proof:yes”> class HandleNodeChanging_FontChanger
implements INodeChangingCallback {<o:p></o:p>

// Implement the NodeInserted handler to set default font settings for every Run node inserted into the Document

public double fSize = 10.0;

public String name = "Arial";

public void nodeInserted(NodeChangingArgs args) throws Exception {

// Change the font of inserted text contained in the Run nodes.

if (args.getNode().getNodeType() == NodeType.RUN) {

Font font = ((Run) args.getNode()).getFont();

font.setSize(fSize);

font.setName(name);

}

}

public void nodeInserting(NodeChangingArgs args) throws Exception {

// Do Nothing

}

public void nodeRemoved(NodeChangingArgs args) throws Exception {

// Do Nothing

}

public void nodeRemoving(NodeChangingArgs args) throws Exception {

// Do Nothing

}

}

public void testNodeChangingInDocument() throws Exception

{

// Create a blank document object

Document doc = new Document(MYDir + "in.docx");

DocumentBuilder builder = new DocumentBuilder(doc);

builder.moveToMergeField("test");

Font fFont = builder.getFont();

HandleNodeChanging_FontChanger obj = new HandleNodeChanging_FontChanger();

// Set up and pass the object which implements the handler methods.

doc.setNodeChangingCallback(obj);

obj.fSize = fFont.getSize();

obj.name = fFont.getName();

// Insert sample HTML content

builder.insertHtml("Hello");

doc.save(MYDir + "Document.FontChanger Out.doc");

}