Skip to main content

How to replace text with images on Word documents using C#

This post it’s a reply to a question I got from a previous post that shows how to work with Word templates from C# code. If you haven’t read it, I recommend to do so because I’m not going into details here. But basically it was about how to create a Word document from a template and perform same text manipulation.

So, the question from Marcel Kieboom was
“Do you know if it would be also possible to replace one of the words with an image which is locally stored?”

The answer is yes, and this is how you can do that.

Based on the same convention I had used in the previous post, I should have a template like this:

What I’m trying to do here is replace the text [angus-young] for an actual pic of Angus. The technique I’m using it’s pretty common on web sites and basically consist in have an image with a matching name for each keyword I want to replace and then create the image path dynamically.

This is the C# code to do that.

* When I execute the find operation I’m using the flag WdReplace.wdReplaceNone. This is important because otherwise we will messed up the current selection and the image will be inserted in the wrong place.

Once you run the code, you will be creating a document called foo.docx inside the bin/debug/docs folder which should look something like this: 

You can grab the code from github. And as usual, questions are more than welcome. Please ping me if you have any trouble using this code.


  1. Nice post. As I searched online, I got alternative method by using Spire.Doc, more details - Replace Images with Texts in Word in C# This post gives a opposite effect but the same subject.

    1. Sounds interesting. I'll check it out. Thanks!

  2. Hi. Can you help me?

    If instead of using a image from a file I used a bitmap created before?
    Thanks. ;)

    1. Hi, MWalker. In that case I'll try to save the bitmap to a file in a tmp folder and use the code as is. When it comes to office interop, the close you play to the VBA way, the better. ;)
      Hope this helps.

  3. My objective was to save processing time. I am dealing with very large structures and it consumes a lot of time save to the hard drive.

    1. Hmmmm, well; In that case I would investigate OpenXML SDK. Although I really dislike it, it might be the right choise for you needs.
      Another option would be using multiple process, but ofcourse, it wouldn't reduce the time to process each file, it'll just lower the processing time of a whole batch at a cost of more processing power. If you can afford power consumption, you should give it a try to this alternative, otherwise, as far as I know, OpenXML it is.
      (Sorry for the late response, I was on vacation).

    2. Than you. ;)
      For now I will save the images then load them. Thank you.
      One more doubt, when using the "Microsoft Word 14.0 Object Library" I get a warning in doc.Close() and app.Quit().


    3. Sure, no problem. Just replace doc.Close() with ((_Document)doc).Close() and app.Quit() with ((_Application)app).Quit()
      (If you are using R# you will get a suggestions saying the cast is redundant, if you remove it, you will get the csc warnings back. Pick one ;))

    4. Hi once again.

      Can you tell me the reason why windows ask me if I want to save the *dotx file everytime I run this code?

      Thank you! ;)

  4. This comment has been removed by the author.

  5. Your post is really helpful for me.
    But how can i replace single keyword for multiple times in single document?

    1. It should work right out of the box. Are you getting any errors or something?

    2. No i am not getting error but i don't know how can i replace single keyword for multiple times in single document.

    3. Just wrap the code with an infinite loop and check at the end of the loop if there are more occurrences of the "target word" (so to speak), if not, then exit.
      I tried this code and it worked for me:

      while(true) {
      //for each keyword you want to replace.
      var keyword = "angus-young";
      Console.WriteLine("Replacing keyword: {0} ...", keyword);
      var sel = app.Selection;

      sel.Find.Text = string.Format("[{0}]", keyword);

      // sel.Find.Forward = true;
      // sel.Find.Wrap = WdFindWrap.wdFindContinue;
      sel.Find.Execute(Replace: WdReplace.wdReplaceNone);

      //This code inserts the image
      var imgPath = Path.GetFullPath(string.Format(@"Img\{0}.jpg", keyword));
      FileName: imgPath,
      LinkToFile: false,
      SaveWithDocument: true);

      //IMPORTANT! =================================================
      //Do we have any other occurrence?
      if (!sel.Find.Execute(Replace: WdReplace.wdReplaceNone))
      break; //We haven't. Exit.
      //IMPORTANT! =================================================

      //finally, save the doc.

  6. Replies
    1. Hi Pankaj, sorry for a late reply. As I commented to other readers, the best way to do it, is to start the macro recorder, do whatever you need by hand, and then peek at the VBA code that the wizard generates for you. I'll try it myself if I have a Windows box at hand, but unfortunately I'm on the mac these days.

  7. How to change text inside Headers and footers ?

    1. Hi Samuel, It's been a long time since I had to work with office so my memory it's a little blurry on this... But what I usually use to do, was to start the macro recorder in word and peek at the generated VBA code. From there, is usually just a copy paste thing. You shouldn't have much trouble with that. (I'll try it myself if I've a Windows box at hand, but these days I'm working on the mac)...

  8. how can page number add in table spire.doc c#


Post a Comment

Popular posts from this blog

Moving to Medium

It's been a long time since I want to give medium a try, and finally, I made some time to do it. To get started on the new platform, I'll be doing series on "Getting programming concepts, languages and tools". If it sounds interesting to you, please take a look at the first post  Getting AWK  and spread the word if you like it. I'm not going to migrate old entries to the new web site. They will remain here safe and sound! As usual, thanks for reading!

Working with unattended reports

In this post I‘ll show you how to create reports that NRapid will execute into an unattended mode. I strongly recommend using this kind of reports in automation scenarios only , and let the user see the print preview dialog in the rest of cases. The only difference between this reports and the standard ones, is that you will cannot make use of dialogs, the runtime will always pass in empty views to the ConfigureReport method. The ConfigureReport method will be executed, but you will have to grab the arguments from somewhere else. The execution pipeline is the same that NRapid uses for standard reports. This is the code to print out the whole list of categories in a dialogless mode. Notice that this report inherits from UnattendedReport class, this class tells to NRapid “run the report unattended”. Also notice that this class comes with a convenience method to configure the report with no arguments. You still can override the one that gets the view data but you will always

How to show excel files inside the .NET Webbrowser Control

If you are reading this, chances are you been banging your head against the wall for a couple of hours (or even days) trying to show excel files inside the WinForms webbrowser control. Possible reasons you ended up in here: You had working code that got broke after upgrading from Win 7. Your code doesn’t work the same way between machines running different (newer) versions of IE. A download box pops up every time your app tries to show an excel file inside the webbrowser control (you wanna show the actual content). You just have no clue on how to get excel working into the .NET embedded webbrowser control. You are trying to implement IInternetSecurityManager and don’t know where to start. (Or how don’t know how to delegate calls to your security manager). Among many other, maybe….. Yes, COM is a PITA, so is ActiveX and IE (Embedded or full for that matter). And no, showing excel files inside the webbrowser control shouldn’t be that hard, but sometimes we have