How to find the text and replace it with image using .NET

How to insert an image to word document by looking an anchor tag in the document?

Let us know if we could search absolute position of an anchor tag in the document and use the position to insert an image. Thanks!

Regards,
Ayaz

@ayazmumtaz

Could you please ZIP and attach your input and expected output Word documents? We will then provide you more information about your query along with code example.

Word document with image placeholder with anchor tag.jpg (60.4 KB)

Hi Tahir, Thanks for quick response!

A sample word document with anchor tag is attached.

Regards,
Ayaz

@ayazmumtaz

Unfortunately, we have not found the input document and expected output Word document in your post except image. Please ZIP and attach the requested document. We will then guide you accordingly.

Word document with image placeholder with anchor tag.zip (24.6 KB)

Hi Tahir,

I have attached the word document.

Regards,
Ayaz

@ayazmumtaz

You can use find and replace feature of Aspose.Words to find the desired text and replace it with image. Following code example shows how to find the text and replace it with image. Hope this helps you.

Document doc = new Document(MyDir + "input.docx");
FindandInsertImage findandInsertImage = new FindandInsertImage();
FindReplaceOptions findReplaceOptions = new FindReplaceOptions();
findReplaceOptions.ReplacingCallback = findandInsertImage;

doc.Range.Replace(@"\s_1\", "", findReplaceOptions);

doc.Save(MyDir + "out.docx"); 

private class FindandInsertImage : IReplacingCallback
{
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
    {
        // This is a Run node that contains either the beginning or the complete match.
        Node currentNode = e.MatchNode;

        // 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.MatchOffset > 0)
            currentNode = SplitRun((Run)currentNode, e.MatchOffset);

        ArrayList runs = new ArrayList();

        // Find all runs that contain parts of the match string.
        int remainingLength = e.Match.Value.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.NextSibling;
            }
            while ((currentNode != null) && (currentNode.NodeType != 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)e.MatchNode.Document);
        builder.MoveTo((Run)runs[0]);
        builder.InsertImage(MyDir + "image.png");

        foreach (Run run in runs)
            run.Remove();

        // Signal to the replace engine to do nothing because we have already done all what we wanted.
        return ReplaceAction.Skip;
    }
}

Thanks Tahir!

This is helpful.

Hi Tahir,

This was helpful.

Could you please provide a Java code snippet to embed an image using find and replace option?

Thanks!
Ayaz

@ayazmumtaz

Following Java code example shows how to find the text and replace it with specific image. Hope this helps you.

Document doc = new Document(MyDir + "input.docx");
FindandInsertImage findandInsertImage = new FindandInsertImage();
FindReplaceOptions findReplaceOptions = new FindReplaceOptions();
findReplaceOptions.setReplacingCallback(findandInsertImage);

doc.getRange().replace("\\s_1\\", "", findReplaceOptions);

doc.save(MyDir + "out.docx");

class FindandInsertImage  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();
        System.out.println(currentNode.getText());
        // 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());

        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)e.getMatchNode().getDocument());
        builder.moveTo((Run)runs.get(0));
        builder.insertImage(MyDir + "image.png");

        // Now highlight all runs in the sequence.
        for (Run run : (Iterable<Run>) 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;
    }
}