We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Calculate TextBox Size in Word Document & Adjust Font Size to Fit Text within Bounds of TextBox (C# .NET)

aspose.wrod check whether textbox render text completely,i need this state,so i can adjust font size.
Thanks

@liu9527,

Please see these sample input/output Word documents (Docs-213870.zip (23.2 KB)) and try running the following code:

Document doc = new Document("E:\\Temp\\input.docx");
DocumentBuilder builder = new DocumentBuilder(doc);

Shape targetShape = (Shape)doc.GetChildNodes(NodeType.Shape, true)[0];
targetShape.Height /= 2; // reduces the height of textbox to half

// Ensure that all Run nodes inside Shape comprise of only one Character
Node[] runs = targetShape.GetChildNodes(NodeType.Run, true).ToArray();
for (int i = 0; i < runs.Length; i++)
{
    Run run = (Run)runs[i];
    int length = run.Text.Length;

    Run currentNode = run;
    for (int x = 1; x < length; x++)
    {
        currentNode = SplitRun(currentNode, 1);
    }
}

// Get the last character in Textbox
// We need to make decision based on the coordinates of this last character
NodeCollection allRunNodes = targetShape.GetChildNodes(NodeType.Run, true);
Run lastRun = (Run)allRunNodes[allRunNodes.Count - 1];

// Bookmark the last character
builder.MoveTo(lastRun);
BookmarkStart start = builder.StartBookmark("_bm");
BookmarkEnd end = builder.EndBookmark("_bm");
lastRun.ParentNode.InsertAfter(end, lastRun);

// calculate the bottom of textbox
LayoutCollector collector = new LayoutCollector(doc);
LayoutEnumerator enumerator = new LayoutEnumerator(doc);

enumerator.Current = collector.GetEntity(targetShape);
float bottomOfShape = enumerator.Rectangle.Bottom;

// calculate the bottom of last character
enumerator.Current = collector.GetEntity(start);
enumerator.MoveNext();
float bottomOfText = enumerator.Rectangle.Bottom;

// Here we will reduce font size until 
// all text fits inside the bounds of Textbox
bool flag = false;
while (bottomOfShape < bottomOfText)
{
    flag = true;

    foreach (Run run in allRunNodes)
        run.Font.Size = run.Font.Size - 1;

    doc.UpdatePageLayout();

    enumerator.Current = collector.GetEntity(start);
    enumerator.MoveNext();
    bottomOfText = enumerator.Rectangle.Bottom;
}

if (flag)
{
    // optionally reduce font size a bit more
    foreach (Run run in allRunNodes)
        run.Font.Size = run.Font.Size - 0.5;
}

doc.Save("E:\\Temp\\20.6.docx");

Hope, this will help in achieving what you are looking for.

thanks, It’s working for me