Search code examples
c#-4.0ms-wordvstoword-2010

Extract images and other components in a Word ContentControl?


c# VSTO

How to insert an image with some caption in a rich text contentcontrol in word 2010. the property formattedtext doesnt even accept a range object


Solution

  • Adding an image to a rich text content control is pretty simple, all you have to do is add it to the Range.InlineShapes collection.

    To retrieve images from a Word document you can do the following:

    1. Loop through all the content controls in the document
    2. If content control has an image, copy it to clipboard
    3. Retrieve the Image object from clipboard
    4. Do any required processing on the image(save to disk,database e.t.c)

    Here's an example:

    Add a reference to System.Windows.Forms.dll to be allow use of the Clipboard class

        string imagePath = @"D:\microsoft.jpg";
        string title = "Microsoft";
        Word.ContentControls cc = this.Application.ActiveDocument.ContentControls;
    
        //Add a rich content control,add an image to the rich content control
        var richContentControl = cc.Add(Word.WdContentControlType.wdContentControlRichText);
        richContentControl.Range.FormattedText.Text = title;
    
        if (System.IO.File.Exists(imagePath))
        {
            Word.InlineShape image = richContentControl.Range.InlineShapes.AddPicture(imagePath);
            image.Height = 70;
            image.Width = 100;
    
            //Retrieve all images from content controls and save to disk
            foreach (Word.ContentControl c in cc)
            {
                if (c.Range.InlineShapes.Count > 0)
                {
                    foreach (Word.InlineShape shape in c.Range.InlineShapes)
                    {
                        shape.Range.Copy();
                        if (System.Windows.Forms.Clipboard.ContainsImage())
                        {
                            System.Drawing.Image clipboardImage = Clipboard.GetImage();
                            string path = System.IO.Path.Combine(@"D:\imageName.jpg");
                            clipboardImage.Save(path);
                        }
                        Clipboard.Clear();
                    }
                }
            }
        }