Replacing image without using Bookmarks

Dear Team,

I have a business requirement and the requirement is to replace the image without using Bookmarks. I want to search for a String and the found String needs to be replaced with image. can you help me to sort this issue?

Hi Kavin,

Thanks for your inquiry.

Yes, you can achieve your requirement by implementing IReplacingCallback interface. Please use the same approach shared at following documentation link to achieve your requirements.
https://docs.aspose.com/words/java/find-and-replace/

Please
check the highlighted section of following code. Hope this helps you. Please let us know if you have any more queries.

If you still face any issue, please share your input and expected
output document here for our reference. We will then provide you more
information on this along with code.

class ReplaceEvaluator implements IReplacingCallback
{
    public int replacing(ReplacingArgs e) throws Exception
    {
        // This is a Run node that contains either the beginning or the complete match.
        Node currentNode = e.getMatchNode();
        // The first (and may be the only) run can contain text before the match,
        // in this case it is necessary to split the run.
        if (e.getMatchOffset() > 0)
            currentNode = splitRun((Run)currentNode, e.getMatchOffset());
        // This array is used to store all nodes of the match.
        ArrayList runs = new ArrayList();
        // Find all runs that contain parts of the match string.
        int remainingLength = e.getMatch().group().length();
        while (
                (remainingLength > 0) &&
                        (currentNode != null) &&
                        (currentNode.getText().length() <= remainingLength))
        {
            runs.add(currentNode);
            remainingLength = remainingLength - currentNode.getText().length();
            // Select the next Run node.
            // Have to loop because there could be other nodes such as BookmarkStart etc.
            do
            {
                currentNode = currentNode.getNextSibling();
            }
            while ((currentNode != null) && (currentNode.getNodeType() != NodeType.RUN));
        }
        // Split the last run that contains the match if there is any text left.
        if ((currentNode != null) && (remainingLength > 0))
        {
            splitRun((Run)currentNode, remainingLength);
            runs.add(currentNode);
        }
        DocumentBuilder builder = new DocumentBuilder((Document)currentNode.getDocument());
        builder.moveTo((Run)runs.get(0));
        builder.insertImage("c:/temp/in.png");
        // Remove runs
        for (Run run : (Iterable) runs)
        {
            run.remove();
        }
        // Signal to the replace engine to do nothing because we have already done all what we wanted.
        return ReplaceAction.SKIP;
    }
    /**
     * Splits text of the specified run into two runs.
     * Inserts the new run just after the specified run.
     */
    private Run splitRun(Run run, int position) throws Exception
    {
        Run afterRun = (Run)run.deepClone(true);
        afterRun.setText(run.getText().substring(position));
        run.setText(run.getText().substring((0), (0) + (position)));
        run.getParentNode().insertAfter(afterRun, run);
        return afterRun;
    }
}
Document doc = new Document(MyDir + "in.docx");

Pattern regex = Pattern.compile("some text", Pattern.CASE_INSENSITIVE);
doc.getRange().replace(regex, new ReplaceEvaluator(), true);
// Save the output document.
doc.save(MyDir + "Out.docx");

Hi Tahir,
Thanks for your response, it helped to achieve my requirement.
Can you please help me to get the soluction for the below query.
I wanted to list the Strings which Starts with ~ and ends with ~ from a document with using Regular expression or without using regular expression.
For example ~agx_xxx_YYY.first_name~.
Thanks in Advance.

Hi Kavin,

Thanks for your inquiry. Please use the following code example to achieve your requirements. Hope this helps you.

Please let us know if you have any more queries.

Document doc = new Document(MyDir + "Test10.docx");
ReplaceCustomTags obj = new ReplaceCustomTags();
doc.getRange().replace( Pattern.compile("~(\\S+)~", Pattern.CASE_INSENSITIVE), obj , false);
for(String text : (Iterable<String>)obj.text)
{
    System.out.println(text);
}
doc.save(MyDir + "Out.docx");
public class ReplaceCustomTags implements IReplacingCallback
{
    public ArrayList text = new ArrayList();
    public int replacing(ReplacingArgs e) throws Exception
    {
        // This is a Run node that contains either the beginning or the complete match.
        Node currentNode = e.getMatchNode();
        // The first (and may be the only) run can contain text before the match,
        // in this case it is necessary to split the run.
        if (e.getMatchOffset() > 0)
            currentNode = splitRun((Run)currentNode, e.getMatchOffset());
        // This array is used to store all nodes of the match.
        ArrayList runs = new ArrayList();
        // Find all runs that contain parts of the match string.
        int remainingLength = e.getMatch().group().length();
        while (
                (remainingLength > 0) &&
                        (currentNode != null) &&
                        (currentNode.getText().length() <= remainingLength))
        {
            runs.add(currentNode);
            remainingLength = remainingLength - currentNode.getText().length();
            // Select the next Run node.
            // Have to loop because there could be other nodes such as BookmarkStart etc.
            do
            {
                currentNode = currentNode.getNextSibling();
            }
            while ((currentNode != null) && (currentNode.getNodeType() != NodeType.RUN));
        }
        // Split the last run that contains the match if there is any text left.
        if ((currentNode != null) && (remainingLength > 0))
        {
            splitRun((Run)currentNode, remainingLength);
            runs.add(currentNode);
        }
        String runText = "";
        for (Run run : (Iterable) runs)
        {
            run.getFont().setHighlightColor(Color.YELLOW);
            runText += run.toString(SaveFormat.TEXT);
        }
        text.add(runText);
        // Signal to the replace engine to do nothing because we have already done all what we wanted.
        return ReplaceAction.SKIP;
    }
    /**
     * Splits text of the specified run into two runs.
     * Inserts the new run just after the specified run.
     */
    private Run splitRun(Run run, int position) throws Exception
    {
        Run afterRun = (Run)run.deepClone(true);
        afterRun.setText(run.getText().substring(position));
        run.setText(run.getText().substring((0), (0) + (position)));
        run.getParentNode().insertAfter(afterRun, run);
        return afterRun;
    }
}