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

Free Support Forum - aspose.com

Search and Replace Text

Hi,

I am trying to search text in the word document and replace the text with an image. But going through examples i did not find an easier way how to do it. This is the first time i am trying to incorporate aspose.word into my application. Please advice.

Thanks

Hi,


Thanks for the inquiry. I think you should use custom evaluator to achieve this. For example see the following code:

public void replaceWithEvaluator() throws Exception

{

String path = "D:\\";

Document doc = new Document( path+ "ResumeMaxCpu.docx");

doc.getRange().replace(Pattern.compile("myString"), new MyReplaceEvaluator(), true);

doc.save(path + "Range.ReplaceWithEvaluator Out.doc");

System.out.print("DOne");

}

private class MyReplaceEvaluator implements IReplacingCallback

{

public int replacing(ReplacingArgs e) throws Exception

{

String is = e.getMatch().group();

Document doc= (Document) e.getMatchNode().getDocument();

DocumentBuilder builder = new DocumentBuilder(doc);

builder.moveTo(e.getMatchNode());

builder.insertImage("D:\\Logo.jpg");

return ReplaceAction.REPLACE;

}

}

Best Regards,


Nabeel Ahmad

Hi,

Thanks for the reply. Is there a way to just replace only one occurance instead of all of the matches.

Thanks,

Rama.

Hi Rama,


Thanks for your inquiry.

You can use code like below to achieve this:

<span style=“font-size:
10.0pt;font-family:“Courier New”;color:blue;mso-no-proof:yes”>private<span style=“font-size:10.0pt;font-family:“Courier New”;mso-no-proof:yes”> class MyReplaceEvaluator
implements IReplacingCallback<o:p></o:p>

{

public int replacing(ReplacingArgs e) throws Exception

{

if(mHasMadeReplacement)

return ReplaceAction.SKIP;

String is = e.getMatch().group();

Document doc= (Document) e.getMatchNode().getDocument();

DocumentBuilder builder = new DocumentBuilder(doc);

builder.moveTo(e.getMatchNode());

builder.insertImage("D:\\Logo.jpg");

mHasMadeReplacement = true;

return ReplaceAction.REPLACE;

}

boolean mHasMadeReplacement = false;

}


Thanks,