Home > .NET > C# Word Automation: Inserting images with text wrapping around

C# Word Automation: Inserting images with text wrapping around

As I work, I keep noting about my work here. Earlier, I wrote about inserting images in a word document at a bookmark in this post. Later, arose the need for having text wrapping around an image if it is small for document width. Solution is to use frames to achieve it and here is how I did it.

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;
            }
        }

 
        public override bool Equals(object obj)
        {
            CImage objToCompare = obj as CImage;
            if (objToCompare == null)
                return false;
            return this.Id.Equals(objToCompare.Id);
        }
    }

Adding frame at end of the document (can be any bookmark for that matter)

Frame wrdFrame = wrdDocument.Frames.Add(wrdDocument.Bookmarks.get_Item(ref oEndOfDoc).Range);

WHERE
wrdDocument
- Active word document object of type : Microsoft.Office.Interop.Word.Document

Setting frame properties for textwrap and autosize

wrdFrame.TextWrap = true;
wrdFrame.VerticalDistanceFromText = 7;
wrdFrame.HorizontalDistanceFromText = 10;
wrdFrame.HeightRule = WdFrameSizeRule.wdFrameAuto;
wrdFrame.WidthRule = WdFrameSizeRule.wdFrameAuto;

Inserting image in frame

Clipboard.SetDataObject(objImage.Bitmap);
wrdFrame.Range.Paste();

WHERE
objImage
- Object of type CImage

And you are done !

Important information

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

Related Posts
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.

Join 400 other followers