Search code examples
javascriptadobe-illustrator

How to shrink a text to fit in a given rectangle in Illustrator via javascript?


I create an areaText via javascript in Illustrator and want to fit text in the given box at the maximum possible size. How to do that?


Solution

  • You can create an overflow area linked to the initial areaText and shrink the size down until there is no more text in that area.

    Example:

    var docRef = documents.add(null,1080,1080);
    var piRef = activeDocument.pathItems;
    var textRefs = activeDocument.textFrames;
    
    var pathRef = piRef.add();
    
    // target text area
    var textArea = piRef.rectangle(940, 140, 800, 600);
    var text = textRefs.areaText(textArea);
    
    // maximum Font size, use something big to shrink down from
    var maxFontSize = 200
    
    text.textRange.characterAttributes.size = maxFontSize;
    
    // create an overflow box
    var overflowArea = piRef.rectangle(940, 140, 800, 600);
    var overflowText = textRefs.areaText(overflowArea, TextOrientation.HORIZONTAL, text);
    
    text.contents = "This text should fit in the box.";
    
    // shrink text size until the overflow box is empty.
    var fontSize = maxFontSize;
    while (overflowText.words.length > 0 && fontSize > 0)
    {
        text.textRange.characterAttributes.size = --fontSize;
        overflowText.textRange.characterAttributes.size = --fontSize;
    }