views:

1864

answers:

2

One of my applications deals with MS Word and Document creation/editing/formatting. I am using Office 2007 w/ VS 2008, and i'm coding against the Microsoft.Office.Interop.Word library, which seems to work with either 2003 or 2008.

I create a Textbox in a Document using the Document.Shapes.AddTextbox method, and then filling it with text. I'd like to be able to programmatically determine whether or not the text fits within the textbox, and if it doesn't, then reduce the font size until it does.

I've tried a couple different methods:

1) using the bool Shape.TextFrame.Overflowing property

while (textbox.TextFrame.Overflowing) // adjust font size

however, this returns TRUE even though when I open the document I can see the text fits in the box.

2) checking the X/Y position of the last character of the text, and seeing if that coordinate falls within the textbox boundaries

lastCharX = System.Convert.ToSingle (tb.TextFrame.TextRange.Characters.Last.get_Information (WdInformation.wdHorizontalPositionRelativeToPage));
lastCharY = System.Convert.ToSingle (tb.TextFrame.TextRange.Characters.Last.get_Information (WdInformation.wdVerticalPositionRelativeToPage));
bool outsideFrameBoundaries = lastCharX + lastCharWidth > frameBoundaryX || lastCharY + lastCharHeight > frameBoundaryY;

however, this returns X/Y that are almost always inside the box, though when I open the document I can't see the character because it doesn't fit in the box.

So I'm running out of ideas here, and i'm asking if anybody else has gone through this before and if they have suggestions for dealing with the inaccurate mess that is the word interop?

A: 

I came up with a solution.

It started when I figured out a method to Word's madness. When I get the X/Y coordinates for a character, and that character exists outside of the textbox area, then Word actually returns the correct X value but the Y value is the Y value of the last visible line on the textbox.

So I scan all characters starting from the end, and if I find duplicate coordinates then I know that there is overflow. I also have to check if the Y-value + the font size is greater than the bottom bound of the textbox. But this seems to work pretty reliably (if slowly) for detecting if a textbox is overflowing. Once I determine if it's overflowing, then I keep decreasing the font size until it is not.

ZaijiaN
A: 

Do you have a sample of the code you created in the solution?