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!

WinForms, paging the DataGridView the right way

I know this may sound like old history, but in the enterprise world there is still a lot of WinForms development. Just a couple of days ago, I had to implement a custom DataGridView capable to work over a butt load of data (100K+ records) and keep responses times acceptables. I thought paging will be a good way to go, and as WinForms is pretty old nowadays, I supposed it will be easy to find a couple examples on the web. While in fact I found examples, all of them were incompletes and/or they wouldn't perform well in real world apps... So I decided to roll my own component and post it online. Hopefully, someone else will find it useful ;). The bread and butter of this solution relies on LINQ and deferred execution. As LINQ takes care of all complicated work, it was quite easy to implement. This component also supports conditional format, sorting and some search capabilities, but in this post I will concentrate on paging only (I'll cover the rest of the features in f

How to create MS Word documents from Office templates using C#

The OpenXML SDK allows you to do pretty much anything you want with office files such as Excel, Word, etc… While many people like this library, I found it complex, unintuitive and poorly documented, not to mention the awful xml format that uses under the hood to represent the documents, styles, etc. So I decided not to use it and build my own solution. If you, like me, don’t like that library, you will find in this post an alternative approach to build word documents from templates using c#. A neat trick to work with Office is to use the macro recorder to understand how things work. The macro recorder allows you to start a macro, do something by hand, stop it, and then take a look at the generated VBA code. Once you do this, you are pretty much set. This is how it looks the template I’am going to use. Note: save the file as a Word template (.dotx) This is the code to create Word documents from C#: By running the code, you should get a document that looks