Auto adjust width for textbox according its text

Below is a sample code i want to create a text field with adjust its width according its text also i have changed its property with code but it is not working can you please help me to resolve this issue

Shape currentShapeTextBox = worksheet.Shapes.AddAutoShape(AutoShapeType.Rectangle, 0, 0, 0, 0, 0, 0);
//set full string set full string to create proper left, center and right
currentShapeTextBox.Text = fnote;
currentShapeTextBox.Font.Size = labelDefaultFontSize;
currentShapeTextBox.HeightPt = 12;
currentShapeTextBox.WidthPt = 113;
currentShapeTextBox.Fill.FillType = FillType.None;
currentShapeTextBox.Line.FillType = FillType.None;
currentShapeTextBox.Font.Color = Color.FromArgb(ffontcolor);
// Set outside width text which is not visible
currentShapeTextBox.TextHorizontalOverflow = TextOverflowType.Clip;
currentShapeTextBox.TextVerticalOverflow = TextOverflowType.Clip;
// Set text direction vertical
currentShapeTextBox.TextOrientationType = TextOrientationType.ClockWise;
currentShapeTextBox.TextBody.TextAlignment.TextVerticalType = Aspose.Cells.Drawing.Texts.TextVerticalType.Vertical;
// Set text alignment
currentShapeTextBox.TextVerticalAlignment = TextAlignmentType.Center;
currentShapeTextBox.TextHorizontalAlignment = TextAlignmentType.Left;
//set radio to Move and Size with Cells
currentShapeTextBox.Placement = PlacementType.MoveAndSize;

currentShapeTextBox.TextBody.TextAlignment.AutoSize = true;
// Disable wrap text (uncheck WordWrap)
currentShapeTextBox.TextBody.TextAlignment.IsTextWrapped = false;

@tejas.patel

Cause

The issue arises from the settings related to the textbox’s autofit behavior. The properties you are using to control the width and wrapping of the text may not be set correctly to achieve the desired effect of auto-adjusting the width based on the text content.

Solution

To ensure that the textbox adjusts its width according to the text, set the AutofitType property to Shape, which allows the shape to resize based on the text. Additionally, enable text wrapping to ensure the text wraps within the bounds of the textbox.

Here’s how you can modify your code:

Code

Shape currentShapeTextBox = worksheet.Shapes.AddAutoShape(AutoShapeType.Rectangle, 0, 0, 0, 0, 0, 0);
currentShapeTextBox.Text = fnote;
currentShapeTextBox.Font.Size = labelDefaultFontSize;
currentShapeTextBox.HeightPt = 12;
currentShapeTextBox.Fill.FillType = FillType.None;
currentShapeTextBox.Line.FillType = FillType.None;
currentShapeTextBox.Font.Color = Color.FromArgb(ffontcolor);

// Set autofit type to resize shape to fit text
currentShapeTextBox.TextBody.TextFrameFormat.AutofitType = TextAutofitType.Shape;

// Enable text wrapping
currentShapeTextBox.TextBody.TextFrameFormat.WrapText = true;

// Set text alignment
currentShapeTextBox.TextBody.TextAlignment.TextVerticalType = Aspose.Cells.Drawing.Texts.TextVerticalType.Vertical;
currentShapeTextBox.TextVerticalAlignment = TextAlignmentType.Center;
currentShapeTextBox.TextHorizontalAlignment = TextAlignmentType.Left;

// Set placement to move and size with cells
currentShapeTextBox.Placement = PlacementType.MoveAndSize;

Next Steps

  1. Implement the changes in your code as shown above.
  2. Test the textbox to ensure it resizes correctly based on the text content.
  3. If you encounter further issues, check the text content length and font size, as they can also affect the textbox size.

Please proceed with these steps, and let me know if you need any further assistance!

getting error when i implement above code in my project

@tejas.patel,

See the following sample code which I used to implement your scenario/case. It works fine and as expected. The shape text is auto-adjusted to its text. Even when I add more (text) lines, it auto-adjusts the height of the shape accordingly. Similarly when I squeeze its width, it adjusts/extends its height to display all text inside it accordingly.
e.g.,
Sample code:

        // Create workbook and worksheet
        Workbook workbook = new Workbook();
        Worksheet worksheet = workbook.Worksheets[0];

        // Your text and font settings
        string fnote = "This is a test string that needs to fit the shape width properly.";
        int labelDefaultFontSize = 10;
        System.Drawing.Color ffontcolor = System.Drawing.Color.Black;

        // Measure the string width using System.Drawing
        float textWidthPixels;
        using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(1, 1))
        {
            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp))
            {
                System.Drawing.Font sysFont = new System.Drawing.Font("Arial", labelDefaultFontSize, System.Drawing.FontStyle.Regular);
                textWidthPixels = g.MeasureString(fnote, sysFont).Width;
            }
        }

        // Convert pixels to points
        float textWidthPoints = textWidthPixels * 72 / 96f; // 1 pixel = 0.75 points (approx)
        float heightPoints = 15; // You can adjust this height

        // Add a rectangle shape with dynamic width
        Aspose.Cells.Drawing.Shape currentShapeTextBox = worksheet.Shapes.AddAutoShape(AutoShapeType.Rectangle, 0, 0, 0, 0, (int)textWidthPoints, (int)heightPoints);

        // Set text and styling
        currentShapeTextBox.Text = fnote;
        currentShapeTextBox.Font.Size = labelDefaultFontSize;
        currentShapeTextBox.HeightPt = heightPoints;
        currentShapeTextBox.WidthPt = textWidthPoints;


        currentShapeTextBox.Fill.FillType = Aspose.Cells.Drawing.FillType.None;
        currentShapeTextBox.Line.FillType = Aspose.Cells.Drawing.FillType.None;
        currentShapeTextBox.Font.Color = ffontcolor;

        currentShapeTextBox.TextHorizontalOverflow = TextOverflowType.Clip;        
        currentShapeTextBox.TextVerticalOverflow = TextOverflowType.Clip;

        // If needed, set text orientation, alignment
        currentShapeTextBox.TextOrientationType = TextOrientationType.ClockWise;
        currentShapeTextBox.TextBody.TextAlignment.TextVerticalType = Aspose.Cells.Drawing.Texts.TextVerticalType.Horizontal;
        currentShapeTextBox.TextVerticalAlignment = TextAlignmentType.Center;
        currentShapeTextBox.TextHorizontalAlignment = TextAlignmentType.Left;

        // Placement
        currentShapeTextBox.Placement = PlacementType.MoveAndSize;

        // Resize shape to fit text and wrapping text on
        currentShapeTextBox.TextBody.TextAlignment.AutoSize = true; 
        currentShapeTextBox.TextBody.TextAlignment.IsTextWrapped = true;

        // Save to file
        workbook.Save("e:\\test2\\out1.xlsx");

Please find attached the output Excel file for your reference.
out1.zip (6.9 KB)

Hope, this helps a bit.

1 Like

@amjad.sahi
now when direction is horizontal then working fine but with vertical not working

// Measure the string width using System.Drawing
float textWidthPixels;
using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(1, 1))
{
	using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp))
	{
		System.Drawing.Font sysFont = new System.Drawing.Font(fontFamily, labelDefaultFontSize, System.Drawing.FontStyle.Regular);
		textWidthPixels = g.MeasureString(fnote, sysFont).Width;
	}
}

// Convert pixels to points
float textWidthPoints = textWidthPixels * 72 / 96f; // 1 pixel = 0.75 points (approx)

													//Event Lable create
Shape currentShapeTextBox = worksheet.Shapes.AddAutoShape(AutoShapeType.Rectangle, 0, 0, 0, 0, 0, 0);
//set full string set full string to create proper left, center and right
currentShapeTextBox.Text = fnote;
currentShapeTextBox.Font.Size = labelDefaultFontSize;
currentShapeTextBox.HeightPt = eventShape.HeightPt;
currentShapeTextBox.WidthPt = (int)textWidthPoints;
currentShapeTextBox.Fill.FillType = FillType.None;
currentShapeTextBox.Line.FillType = FillType.None;
currentShapeTextBox.Font.Color = ColorTranslator.FromOle(ffontcolor);

// Set outside width text which is not visible
currentShapeTextBox.TextHorizontalOverflow = TextOverflowType.Clip;
currentShapeTextBox.TextVerticalOverflow = TextOverflowType.Clip;

if ((shapeLabelType == "UPPER" && (upperLblAligmnet == 3 || upperLblAligmnet == 4 || upperLblAligmnet == 5)) ||
	(shapeLabelType == "LOWER" && (lowerLblAligmnet == 3 || lowerLblAligmnet == 4 || lowerLblAligmnet == 5)))
{
	// Set text direction vertical
	currentShapeTextBox.TextOrientationType = TextOrientationType.ClockWise;
	currentShapeTextBox.TextBody.TextAlignment.TextVerticalType = Aspose.Cells.Drawing.Texts.TextVerticalType.Vertical;

	// Set text alignment
	currentShapeTextBox.TextVerticalAlignment = TextAlignmentType.Center;
	currentShapeTextBox.TextHorizontalAlignment = TextAlignmentType.Left;
}
else
{
	// Set text direction horizontal
	currentShapeTextBox.TextOrientationType = TextOrientationType.NoRotation;

	// Set text alignment
	currentShapeTextBox.TextVerticalAlignment = TextAlignmentType.Center;
	currentShapeTextBox.TextHorizontalAlignment = TextAlignmentType.Left;
}

currentShapeTextBox.Font.Name = fontFamily;

//set radio to Move and Size with Cells
currentShapeTextBox.Placement = PlacementType.MoveAndSize;

currentShapeTextBox.TextBody.TextAlignment.AutoSize = true;
// Disable wrap text (uncheck WordWrap)
currentShapeTextBox.TextBody.TextAlignment.IsTextWrapped = false;

@tejas.patel
If the direction is vertical , please set height as measured size.

@simon.zhao
can you give me sample code? for vertical direction

@tejas.patel
Please refer to the following example code and check the attachment. result.zip (17.0 KB)

// Create workbook and worksheet
Workbook workbook = new Workbook(filePath + "test.xlsx");
Worksheet worksheet = workbook.Worksheets[0];
Shape shape = worksheet.Shapes[0];
            
int labelDefaultFontSize = shape.Font.Size;
System.Drawing.Color ffontcolor = shape.Font.Color;

// Measure the string width using System.Drawing
float textWidthPixels;
using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(1, 1))
{
    using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp))
    {
        System.Drawing.Font sysFont = new System.Drawing.Font(shape.Font.Name, labelDefaultFontSize, System.Drawing.FontStyle.Regular);
        textWidthPixels = g.MeasureString(shape.Text, sysFont).Width;
    }
}
// Convert pixels to points
float textWidthPoints = textWidthPixels * 72 / 96f; // 1 pixel = 0.75 points (approx)
shape.HeightPt = textWidthPoints;

// Save to file
workbook.Save(filePath + "out_net.xlsx");

Hope helps a bit.

1 Like

@John.He
Thank you

@tejas.patel
You are welcome. If you have any questions, please feel free to contact us at any time.

1 Like

The issues you have found earlier (filed as CELLSNET-58724) have been fixed in this update. This message was posted using Bugs notification tool by leoluo