Programmatically adjust the font size to fit the text inside a text box in Word

One of my applications deals with creating and editing / formatting MS Word and documents. I am using Office 2007 w / VS 2008 and I am coding for a Microsoft.Office.Interop.Word library that seems to work since 2003 or 2008.

I am creating a textbox in a document using the Document.Shapes.AddTextbox method and then filling it with text. I would like to be able to programmatically determine if the text in the textbox is appropriate, and if not, reduce the font size until it does.

I've tried a couple of different methods:

1) using bool property Shape.TextFrame.Overflowing

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

      

however, this returns TRUE, although when I open the document I can see that text is being inserted into the field.

2) by checking the X / Y position of the last character of the text and seeing if that coordinate falls within the bounds of the text box

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, which are almost always inside the box, although 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 and I'm asking if anyone else has gone through this before and if they have any suggestions for dealing with the imprecise mess that is the word interop?

+1


source to share


1 answer


I came up with a solution.

It started when I understood the Word madness method. 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 in the textbox.



So, I loop through all the characters starting from the end, and if I find duplicate coordinates, I know there is an overflow. I also have to check if the Y value + font size is greater than the bottom border of the textbox. But it works pretty reliably (if slow) for textbox overflow detection. Once I determine if it is overflowing, I keep decreasing the font size until it does.

+1


source







All Articles