Replace Text in Word DOCX Document with JPEG GIF PNG Images using C# .NET Code

I want to replace a particular text in a document, say , with an image.


Using MS Word automation I could do a search for the text using Selection.Find(), which would move the cursor to my search text, then I could insert an inline image. In Aspose, I can’t seem to find a function that let’s me search for text. Any help?

Hi John,

Thanks for your inquiry. Sure, you can achieve this by using the following code snippet:

Document doc = new Document(@"C:\temp\in.docx");
doc.Range.Replace(new Regex(@""), new ReplaceWithImageEvaluator(), false);
doc.Save(@"C:\temp\out.docx");
private class ReplaceWithImageEvaluator : IReplacingCallback
{
    ///
    /// NOTE: This is a simplistic method that will only work well when the match
    /// starts at the beginning of a run.
    ///
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
    {
        DocumentBuilder builder = new DocumentBuilder((Document)e.MatchNode.Document);
        builder.MoveTo(e.MatchNode);
        // Replace 'text to replace' text with an image.
        Shape img = builder.InsertImage("http://www.aspose.com/images/aspose-logo.gif");
        e.Replacement = "";
        return ReplaceAction.Replace;
    }
}

I hope, this helps.

Best regards,

A post was split to a new topic: Replace text in Word document with image

This method signature doesn’t exist. The solution does not work.

@Sunhillow Yes, you are right, the signature of Range.Replace method has been changed. Now, you should set IReplacingCallback as a property in FindReplaceOptions. I have provided a working code example in this thread:
https://forum.aspose.com/t/search-replace-text-string-in-word-docx-document-with-bmp-png-images-using-c-net/216965/4

Thank you. It seems the confusion is due to search engines and forwarding pages. Is it possible to remove these legacy pages or tag them to be excluded in searches?

@Sunhillow Thank you for your suggestion. The code provided in this thread is actually correct and might be useful for users who uses older versions of Aspose.Words. But you are right, we will consider improving search on the forum.