How to make font size resize automatically to fit in a text box in photoshop using script

I have a JSON file like this:

{
    "text": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam dui ante, euismod id quam eu. "
}

I have 6 different Photoshop file (.psd) with completely different template and design.

Each psd file have a paragraph text box of size say

  1. 600px X 600px

  2. 500px X 500px

  3. 400px X 400px

and so on. They all have different sizes of bounding box. (They don’t have exact square size as mentioned above.)

I am writing a script which takes the text object from JSON and changes the text content of these paragraph text boxes.

// Include the JSON Parser
#include json2js.js

var originalunit = preferences.rulerUnits;
preferences.rulerUnits = Units.PIXELS;

// function to read json
function loadJson(relpath){
    var script = new File($.fileName);
    var jsonFile = new File(script.path + '/../json/' + relpath);

    jsonFile.open( 'r' );
    var str = jsonFile.read();
    jsonFile.close();

    return JSON.parse(str);
}

// Read the JSON
var json = loadJson( 'test.json' );

var docRef = app.activeDocument;
var layerRef = docRef.artLayers.getByName( 'text' );

layerRef.textItem.contents = json.text;
layerRef.rasterize(RasterizeType.TEXTCONTENTS);

var textHeight = layerRef.bounds[2] - layerRef.bounds[0];
var boundHeight = layerRef.textItem.height;

var currentFontSize = layerRef.textItem.size;
currentFontSize = currentFontSize.toString().replace(" pt", "");


if(textHeight > boundHeight) {
    fitText(textHeight, boundHeight, currentFontSize, layerRef, json);
 }

//function to fit text inside the  box
function fitText(textHeight, boundHeight, currentFontSize, layerRef, json){
    while(textHeight > boundHeight) {
        currentFontSize--;
        layerRef.textItem.size = currentFontSize;
        layerRef.textItem.contents = json.text;
        textHeight = layerRef.bounds[2] - layerRef.bounds[0];
    }
 }

I have set the font-size of text box, so that 15 character can perfectly fit in the box.

But the text object can change to any number of character, say 30, 50 or 70 character. Since, the size of the text box and the font size is fixed in the template,

How can I resize the font-size to automatically fit any number of character within the text box ?

Answer

Attribution
Source : Link , Question Author : user123456987 , Answer Author : Community

Leave a Comment