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.

Comments

  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.

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

      Delete
  2. Hi. Can you help me?

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

    ReplyDelete
    Replies
    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.

      Delete
  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.

    ReplyDelete
    Replies
    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).

      Delete
    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().

      Regards,

      Delete
    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 ;))

      Delete
    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! ;)

      Delete
  4. This comment has been removed by the author.

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

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

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

      Delete
    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);
      sel.Range.Select();

      //This code inserts the image
      var imgPath = Path.GetFullPath(string.Format(@"Img\{0}.jpg", keyword));
      sel.InlineShapes.AddPicture(
      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.
      doc.SaveAs(Path.GetFullPath(@"Docs\foo.docx"));
      doc.Close();

      Delete
  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.

      Delete
  7. How to change text inside Headers and footers ?

    ReplyDelete
    Replies
    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)...

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

    ReplyDelete

Post a Comment

Popular posts from this blog

Migrating an ASP.NET MVC 4 app from Azure websites to WinHost

About a week ago I've to migrate an ASP.NET MVC 4/EF5 application from Azure websites to WinHost. While the process was really smooth, there were some caveats related to database connections that I want to share with you. Create and setup the ftp profile on VS and configure the connection string was really easy, WinHost provide you those values and there is nothing special here. But once you deploy your website and try to see it online, you may get the “yellow screen of dead” with the message: "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)" Assuming you wrote the connection string properly, this happens because you cannot use the default connection name in your web.c

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