Opening and inserting a picture in word document programmatically using C#


Create a new windows application project and add a button to it.

On click of that button, we will open a document and insert a picture to it.

(In the doc file insert a table at the location where you want the picture to appear.)

Than add reference to (Word 10.0 or 11.0 object library) within COM tab of Add reference dialog box.

After adding reference, add this directive

using Microsoft.Office.Interop.Word

Put the following code in the button click event handler

// For optional parameters create a missing object

object missing = System.Reflection.Missing.Value;

// Create an object for filename, which is the file to be opened

object fileName=@”C:\MySecond.doc”;

// Create an object of application class

ApplicationClass WordApp = new ApplicationClass();

// open the document specified in the fileName variable

Document adoc = WordApp.Documents.Open(ref fileName, ref missing, ref missing, ref missing, ref missing,

ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,

ref missing, ref missing, ref missing);

// We can insert the picture using Range objects AddPicture method

// To insert a picture at a particular location in the word document

// insert a table over there and then refer that location through range object

Range rngPic = adoc.Tables[1].Range;

// we can even select a particular cell in the table

//Range rngPic = rng.Tables[1].Cell(2, 3).Range;

rngPic.InlineShapes.AddPicture(@”C:\anne_hathaway.jpg”, ref missing, ref missing, ref missing);

WordApp.Visible = true;

 

Bye

 

Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

39 thoughts on “Opening and inserting a picture in word document programmatically using C#”

  1. Is there also a possibility like this for web application?
    I have a generated image from a chart component that i need to add to a word document and then let the user save it.

    Greets

    Like

  2. Hi Experts,

    I want to inser the picture in excel but if i mention in the cell “F5″ as Image1. when i click the macro image1.jpg should appear in cell :a5:d10”

    Please do the needful

    regards,
    Arul

    Like

  3. Hi Nishant

    How i will add one blank extra page in word document using C#.Net

    Please give me reply.

    thx

    Like

  4. Hi
    I can add apicture to a word document from file.
    How can I add a picture to a Word document if it is already loaded and is stored in a System.Drawing.Image parameter?

    Like

  5. Nice article and really helpfu. keep it up. How to format paragraph with starting with numbering ie 1, 2, followed by tabspace for first line then continue with second line with left indent at zero inche in C#.

    1. text with justfied….
    second line ,……..

    2. text with justified….

    Thank if you coudl help me.

    Like

    1. nice artical,
      But i want know how can i add a picture when click button it’s automatically show in word document…
      here given your code not work which i want..
      plz.. help me.

      Like

  6. hi nishant Rana
    i want to obtain the height and width of cell i mean
    cell of word table so i can scale the picture then inserted to be fitted exactly to the cell
    i think i could find the width but i faild to find the height thanks in advanced

    Like

  7. hi nishant Rana
    i want to obtain the height and width of cell (in c#)i mean
    cell of word table so i can scale the picture then inserted to be fitted exactly to the cell
    i think i could find the width but i faild to find the height thanks in advanced

    Like

  8. I would like to download all the image files attached in Microsoft CRm 4.0 web site and show them on the MS Word.
    i have used the third party component called CRM Documents Core Pack Add-ons to generate MS Word report.
    every time i try to save the “documentbody” from the FilteredAnnotation table into a Stream object i am gettign error . Can anyone help me to handle BLOB (Binary Large Object) to an image file in MS Word using Microsoft VBA

    Like

    1. hy ,

      i am writing an application , in that i am passing images . that image contain text and picture ( eg. football , small baby , group of people ) . i am able to extract the text inside that image and save it to word document but when comes to picture in that image , it gives me blank in word file .

      i am using MODI ( Microsoft Office Document Imaging )

      any one who know the solution please reply . i need the solution . please .

      .Ritesh Jaiswal

      Like

  9. hi,
    The code is not working in VS2010 and there is an error on line
    ApplicationClass WordApp = new ApplicationClass();
    Error Description:
    Interop type ‘Microsoft.Office.Interop.Word.ApplicationClass’ cannot be embedded. Use the applicable interface instead.

    if any one can solve plz help…
    Thanks in advance.

    Like

  10. For simple scenarios this is simple enough solution. But the problem of Office COM is still present which means this solution shoud be avoided whenever possible. There are 3rd party COM free solutions on the market or OpenXML SDK from Microsoft.
    Since Open XML SDK seems easy to program against – it’s not and many solution based on it end up in producing corrupt documents, but In my oppininion still a better way than Office COM.
    On the other side most ready-to-use tools and components are 3rd party and are not free solutions (except for http://flexdoc.codeplex.com/) and some of them are also pretty expensive.
    For all how are looking for a templating based solution (no coding for inserting pricture, text, …, just place tags/placeholders on the template) I would recommend to see http://www.docentric.com. It’s a COM free, very easy to use with the Add-In for MS Word and quite affordable.
    It doesn’t matter so much which solution you pick as long as you keep away from Office COM.

    Like

  11. Am able to insert the picture in word document.BUt i want add the picture at the end of the document using asp.net

    Like

  12. Hii… I am getting an error : The graphics filter was unable to convert this file. when trying to insert picture… Could you please help me

    Like

  13. Hi Nishant,

    My MS word file shown like below format

    #A# #B# #C# #D# #E#

    I have implemented below code to replace text in MS word file using C#.

    public void ReplaceWordDoc()
    {
    object missing = Missing.Value;
    Document doc = Globals.ThisAddIn.Application.ActiveDocument;

    List search = GetSearchList();

    foreach (var searchItem in search)
    {
    foreach (Range tmpRange in ((Document)doc).StoryRanges)
    {
    tmpRange.Find.ClearFormatting();
    tmpRange.Find.Text = searchItem.Find;
    tmpRange.Find.Replacement.ClearFormatting();
    tmpRange.Find.Replacement.Text = searchItem.Replace;
    object replaceAll = WdReplace.wdReplaceAll;

    if (searchItem.Replace.Contains(“gif”))
    {
    tmpRange.InlineShapes.AddPicture(searchItem.Replace, Type.Missing, Type.Missing, tmpRange);
    }
    else
    {
    tmpRange.Find.Execute(ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing, ref replaceAll, ref missing, ref missing, ref missing, ref missing);
    }
    }
    }
    }

    private List GetSearchList()
    {
    List ilst = new List();
    for (int i = 0; i <= 4; i++)
    {
    ReplacerSearch ObjReplacerSearch = new ReplacerSearch();
    if (i == 0)
    {
    ObjReplacerSearch.Find = "#A#";
    ObjReplacerSearch.Replace = "ABCD";
    }
    else if (i == 1)
    {
    ObjReplacerSearch.Find = "#B#";
    ObjReplacerSearch.Replace = "EFGH";
    }
    else if (i == 2)
    {
    ObjReplacerSearch.Find = "#C#";
    ObjReplacerSearch.Replace = "IJKL";
    }
    else if (i == 3)
    {
    ObjReplacerSearch.Find = "#D#";
    ObjReplacerSearch.Replace = "MVC Developer";
    }
    else if (i == 4)
    {
    ObjReplacerSearch.Find = "#E#";
    ObjReplacerSearch.Replace = "D:\\ajax_loader.gif";
    }

    ilst.Add(ObjReplacerSearch);
    }
    return ilst;
    }

    My MS word out put is like,

    [Image File] #ABCD# #EFGH# #IJKL# #MVC Developer# #E#

    I need image at place of #E# not on the start.

    or refer below link,

    http://stackoverflow.com/questions/16456792/find-specific-text-and-replace-with-image-file-in-ms-word

    Like

    1. I got the solution,

      public void ReplaceWordDoc()
      {
      object missing = Missing.Value;
      Document doc = Globals.ThisAddIn.Application.ActiveDocument;

      List search = GetSearchList();

      foreach (var searchItem in search)
      {
      foreach (Range tmpRange in ((Document)doc).StoryRanges)
      {
      tmpRange.Find.ClearFormatting();
      tmpRange.Find.Text = searchItem.Find;
      tmpRange.Find.Replacement.ClearFormatting();
      tmpRange.Find.Replacement.Text = searchItem.Replace;
      if (searchItem.Replace.Contains(“gif”))
      {
      tmpRange.Find.Replacement.Text = “”;
      Object end = doc.Characters.Count;
      Range tmpRange1 = doc.Range(0, ref end);
      Find fnd = tmpRange1.Find;
      fnd.ClearFormatting();
      fnd.Text = searchItem.Find;
      fnd.Execute(ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
      ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

      tmpRange1.InlineShapes.AddPicture(searchItem.Replace, Type.Missing, Type.Missing, Type.Missing);
      }
      tmpRange.Find.Execute(ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
      ref missing, ref missing, ref missing, WdReplace.wdReplaceAll, ref missing, ref missing, ref missing, ref missing);
      }
      }
      doc.Close(ref missing, ref missing, ref missing);
      }

      private List GetSearchList()
      {
      List ilst = new List();
      for (int i = 0; i <= 4; i++)
      {
      ReplacerSearch ObjReplacerSearch = new ReplacerSearch();
      if (i == 0)
      {
      ObjReplacerSearch.Find = "#A#";
      ObjReplacerSearch.Replace = "ABCD";
      }
      else if (i == 1)
      {
      ObjReplacerSearch.Find = "#B#";
      ObjReplacerSearch.Replace = "EFGH";
      }
      else if (i == 2)
      {
      ObjReplacerSearch.Find = "#C#";
      ObjReplacerSearch.Replace = "IJKL";
      }
      else if (i == 3)
      {
      ObjReplacerSearch.Find = "#D#";
      ObjReplacerSearch.Replace = "Developer";
      }
      else if (i == 4)
      {
      ObjReplacerSearch.Find = "#E#";
      ObjReplacerSearch.Replace = "D:\\ajax_loader.gif";
      }

      ilst.Add(ObjReplacerSearch);
      }
      return ilst;
      }

      Like

  14. I tend not to write many remarks, however I browsed some
    of the comments on this page Opening and inserting a picture in word document programmatically using C# | Nishant Rana’s Weblog.
    I do have some questions for you if you do not mind. Is it
    simply me or does it appear like a few of these remarks look like they are written
    by brain dead folks? 😛 And, if you are posting on additional online
    sites, I’d like to follow anything new you have to post.
    Could you list of the complete urls of all your public pages like your twitter
    feed, Facebook page or linkedin profile?

    Like

  15. Hello There. I discovered your blog the usage of msn. That
    is an extremely neatly written article. I will be sure to bookmark it and return to learn extra of your useful information.
    Thank you for the post. I’ll definitely comeback.

    Like

  16. In The Hunger Games, Sutherland stars as President Snow, and
    he realized the impact the film would have after he began to tell
    people he was in it. Wilde’s Creepy House, a full-scale haunted house
    with live actors, is guaranteed to send chills up
    and down your spine when it debuts October 17 from 11 a.
    Tens of thousands of military officials in uniforms stand still waiting
    at the plaza in front of the palace. When filing for a chapter 7 with your attorney Tyler, TX, for instance,
    here are a few of the things that might happen. Friendships develop; tips are shared about grooming, vets, foods,
    treats – and not just for the pets. That way, when something changes, you
    will hopefully be able to identify what is no longer “normal. For example in Rome Total War, if someone plays as Rome, it means they’re playing as the ‘Rome class’, the same applies for the other factions. He demands to know why she never slept with her first husband, the deceased Renly Baratheon. Use rubber cement to securely connect the fins to the soda bottle or your choice of cylindrical object. One is to end the game, and allow the game to be called a draw. The main difference between Netflix and Gamefly is that the price goes up from the introductory price. If you come in all guns blazing, then this boat for you. Once he returns to his human skin the warg reveals the destruction and death that surrounds the black brother’s former encampment at the Fist of the First Men. Twilight Prince (personal opinion) doesn’t count because the game was originally from Game – Cube and then transfer in to the Wii console. Essentially, Microsoft gives snoops, hackers, advertisers, usage trackers and terrorists the upper hand over oblivious users. Casual games are played on PC online with free trials or the expense of buying games in web browsers. It wouldn’t be the Tokyo Game Show without the RPGs. We are serving for years to provide wow accounts to all of customers. This just in from Fox News:Joe the Terrorist just got refused. Therefore, whatever you choose, the key point is that you have to use it in order to make the event livelier and more fun. Some of these choices have simpler explanations than others. Game creators who are familiar with the Game – Cube or Wii will be right at home crafting games for the new handheld. They are typically either ceramic (guests sign with marker) or silver (come with engraving tool). All Castaway rods come with a whole lot of technical innovation and improvement behind them. which shook looseagain after a mere ten minutesat the insatiable blue countersof your local Walmart crack pipe dealer.

    Like

  17. Its true, more than half of all people who start a jogging program
    get an injury within 6 weeks. “In actual racing we’ve got [an equivalent] of quests, which are in race objectives. Almost instantly after the game starts, the player finds himself in a frenzy because of all those shifting of gears, flooring of gas pedals and the crazy maneuvering of the cars through the other competitors.

    Like

  18. And for those of you in the minority that don’t care, don’t understand,
    and call it soccer, let me point out somrthing that you might have missed:
    soccer players are reallpy hot. I am good at sharing Jesus and spiritual
    concepts with people who are not Christian’s. No matter what the scenario yyou want, you can find it
    when you pkay hunting games on the internet. Whalee tells Emma the
    patient made it and is waking up. Coronado’s cask Idiot IPA slacked
    my thirst wwith a vengeance. How can average readers, who aren’t
    medical doctors or Ph. Misc:Olympic Medals Certificate of
    Olympic Achievement Olympic Themed Writing paper.
    Dont let a difficult level oon a online game detract from this reelaxing activity.
    Is this a step forward for Lara orr will her fans fight to
    get the old Lara back. There is a general assumption that, unless otherwise specifically stated,
    fixtures will remain in the propertyy andd fittings will
    be taken by the vendor. But, she says they don’t worry about those risks and don’t ake the tests.

    Thiis upsets Nucky, who we later see having an affair with Billie Kent (Meg Steedle), a new character in the
    season. Girls will engage guys in different games when they are attracted
    to them. But still, it would bbe nice to hand out a memmento
    of the special occasion. John Koller: With the strength
    and volume of the rich Play – Station 2 lineup, there are obviously fans out there who would love
    to get their hands on these fan-favorite titles again. The principle
    theme music performed uring the game iss similar music erformed throughout the scenes in the first Despicable Me when the Minions hurry to fulfill Gru.*He had ttwo game-winning RBI and one game-tying RBI
    in the sweep. The Dark Knigyt Rses Blu-ray Steel – Book with “The Dark Knight Reborn” documentary.
    He leads the SEC with 89 innings pitched and ranks in the top five nationally with 0.
    Gyp immediately wants to talk business, but Nucky gsts pulled away ffor another ordeal.

    Youth aand inexperience surrounding the trio could cause some fluctuation-
    sometimes ffar too much for the hesd coach. The approximate charge time is a reasonable 2 hours and can bee
    charged via a laptop or home computer. Dress upp games foor girls prepare for
    you many famous Hollywood actors and actresses for you to deseign fashion style
    ffor them. Girls cann go here to choosee the suitable desiggns for her boyfriend, or
    jst for fun. Add to this a dark room and nothing
    more than a crowbar for self defense and tthe heart starts to beat way fasrer than it was before.

    Like

Please share your thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

CRM for You and Me

Customer Relationship Mgt App for the Professional

D CRM Explorer

Learn about Microsoft Dynamics CRM Power Platform customization and implementation and other cool stuffs

Stroke // Jonas Rapp

I know pre-stroke. I will improve who I was.

Power Melange

Power Melange By Shalinee

Clavin's Blog

Power Automate - Power Apps - SharePoint Online - Azure - Nintex - K2 - Artificial Intelligence

Sat Sangha Salon

An Inquiry in Being

The Indoencers

The Influencers & Influences of Indian Music

Monika Halan's blog

Hand's-free money management

D365 Demystified

A closer look at Microsoft Dynamics 365.

Microsoft Mate (msftmate) - Andrew Rogers

Experienced consultant primarily focused on Microsoft Dynamics 365 and the Power Platform

Knowhere365

Specific topics by Django Lohn on the whole Microsoft365 Stack

Manmit Rahevar's Blog

One Stop Destination for Microsoft Technology Solutions

MG

Naturally Curious

Brian Illand

Power Platform and Dynamics 365

Steve Mordue MVP

A Microsoft Business Applications MVP

Subwoofer 101

Bass defines your home theater

SQLTwins by Nakul Vachhrajani

SQL Server tips and experiences dedicated to my twin daughters.

Everything D365

Discovering Azure DevOps and D365 Business Applications

Tech Wizard

Lets do IT Spells

Two Bite Tips

Valuable Tips To Grow Your Business

XRM Tricks (Power Platform & Dynamics CRM )

Power Platform & Dynamics CRM

CRM TIPS BY PRM

Mail to crmtipsbyprm@gmail.com for queries and suggestions

nijos.dev

Giving back to the community what I have learned

xrm CRM Dynamics

Dynamics CRM Technical & Functional Info

Dynamics 365 Blogs - Explained in unique way

Sometimes you need to look at things from different perspective.

CRM Keeper

Dynamics 365 Customer Engagement, CRM, Microsoft CRM, Dynamics CRM

EVOLVED365

Step into the world of a Dynamics 365 Consultant

Dianamics PCF Lady

Diana & Dynamics 365 & Power Platform

Sara Lagerquist

No Code Customization Concepts

innovativeaj

developer, designer, writer, fun loving, patriotic, humble and a sweet person inside out :) love and respect people who have a great sense of humor.

Temmy Wahyu Raharjo

Dreaming to be a clean coder and TDD minded programmer.

Transform 365

We blog about problems we face and code we write to help others

%d bloggers like this: