Home > .NET > C# Word Automation: Inserting Images

C# Word Automation: Inserting Images

I was looking for a way to insert images at a bookmark in a word document and thought should document these for future reference

CImage class Definition

public class CImage
{
        public string Path
        {
            get;
            set;
        }

        public decimal Id
        {
            get;
            set;
        }

        public string Title
        {
            get;
            set;
        }

        public Image Bitmap
        {
            get;
            set;
        }

        public bool BusyLoading
        {
            get;
            set;
        }

        public void GetImage()
        {
            try
            {
                BusyLoading = true;
                WebRequest req = WebRequest.Create(Path);
                WebResponse response = req.GetResponse();
                Stream stream = response.GetResponseStream();

                Bitmap = Image.FromStream(stream);
                stream.Close();
            }
            catch
            {
                Bitmap = null;
            }
            finally
            {
                BusyLoading = false;
            }
        }
}

Scenario 1:
You have a path of the image file which is to be inserted

public static void SetBookMark(Document p_objWordDocument, string p_strName,
          CImage p_objImage)
        {
            if (p_objWordDocument.Bookmarks.Exists(p_strName))
            {
                object objBookMark = p_strName;
                p_objWordDocument.Bookmarks.get_Item(ref objBookMark).Range.InlineShapes.AddPicture(p_objImage.Path, ... dozons of object params ...);
            }
        }

Scenario 2:
When you have the bitmap in memory

public static void SetBookMark(Document p_objWordDocument, string p_strName,
           CImage p_objImage)
        {
            if (p_objWordDocument.Bookmarks.Exists(p_strName))
            {
                object objBookMark = p_strName;
                Clipboard.SetDataObject(p_objImage.Bitmap);
                p_objWordDocument.Bookmarks.get_Item(ref objBookMark).Range.Paste();
            }
        }

Important information

You need to add a COM reference to your favorite word object library which should in turn add

Related Posts
Advertisement
Categories: .NET

Leave a Reply

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

Follow

Get every new post delivered to your Inbox.