I know I said I'd talk about tables next, but I'll do those later. For now I want to discuss just a few handy little things I picked up along the way.
Putting Images in a Word Doc
Someone asked about this in the comments to my last post. I don't know that this is the *best* way to put images in the document, but it's the easiest way I've found, with the least intrusive amount of code:
//get Range for your insert point, like via bookmark
Object bookmark = "InsertRange";
Range insertRange = wordDocument.Bookmarks.get_Item(ref bookmark).Range;
//get a System.Drawing.Image
//obviously you could get the image elsewhere, like from compiled resources, disk, memory, etc
Image img = System.Drawing.Image.FromFile(imageURI);
//and now the magic System.Windows.Forms.Clipboard.SetImage(img);
insertRange.Paste();
Basically, get your image in memory, copy it to the clipboard, and paste it into the document where you want it. Range.Paste() is pretty handy for hacking around.
Alternatively, you can use InlineShapes to add a picture:
Range.InlineShapes.AddPicture(imagePath, ref oMissing, ref oMissing, ref oMissing);
But I have found that the copy/paste method, while probably not as performant, is easier to control. If you paste an image into a document it takes whatever constraints are on it (like table size constraints, for instance) and just deals. I have not found that to always be the case with InlineShapes.AddPicture() so I prefer the copy/paste method for consistency.
Inserting a horizontal line is easy, one line of code:
Range.InlineShapes.AddHorizontalLineStandard(ref RangeEnd);
With InlineShapes, you can also add Charts, Pictures, and other interesting things.
Learning About Your Document with get_Information
Ok, let's say you want to do something based on the positioning of an element on the page. In my case, I wanted to stop inserting text in one table, and start inserting into another table, when the text in the first table reached close to the bottom of an image in another column. The end result is a "smart" wrapping effect on the document.
To find where an object is relative to the top of the page, simply get the Range (imagine that) and use get_Information:
float objectPosition = (float)insertRange.get_Information(WdInformation.wdVerticalPositionRelativeToPage);
Using that line of code you can find where you are on the document and get information about where other objects are as well.
To find your current page number (or the page number on which your current range ends) you simply:
int currentPage = (int)insertRange.get_Information(WdInformation.wdActiveEndPageNumber);
There are a lot of interesting (and confusing) available values in WdInformation, check them out and play around.
Okay, that's that. Once you find yourself in the area of needing information like WdInformation.wdVerticalPositionRelativeToPage you will find that you really wish you didn't need that information.
Next time = tables.
Tags:
Word Interop Code