Posted by: Nishant Rana | July 17, 2008

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

 


Responses

  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

  2. Hi, it’s very useful to me…Thanks

  3. Nice Article, really helpful to me, keep continue.
    Thanks

  4. Its great

  5. I really liked the way you presented. I have got what I want. Thank you very much

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

  7. Hi,

    Really nice article………….

    Cheers!!!

    Ujjwal B Soni

  8. well, hi admin adn people nice forum indeed. how’s life? hope it’s introduce branch ;)

  9. thx , it’s nice code and easy to understand , thx

  10. Hi Nishant

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

    Please give me reply.

    thx

  11. 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?

  12. Nice Article. It was really helpful


Leave a response

Your response:

Categories