Mobile app version of vmapp.org
Login or Join
Kevin459

: How to make font size resize automatically to fit in a text box in photoshop using script I have a JSON file like: { "text": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.

@Kevin459

Posted in: #AdobePhotoshop #PhotoshopScripting

I have a JSON file like:

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


The text object above contain 15 character. And, I have 6 different Photoshop file (.psd) with completely different template and design.

Each psd file have a paragraph text box of size say

1st => 600px X 600px

2nd => 500px X 500px

3rd => 400px X 400px

...

and so on. They all have different size of bounding box. (They don't have exact square size as mentioned above, in actual they are of sizes like 500px X 120px or 300px X 750px, They are of different sizes)

I am writing a script using JavaScript which take the text object from JSON and change the text content of these paragraph text box.

// 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 ?

10% popularity Vote Up Vote Down


Login to follow query

More posts by @Kevin459

0 Comments

Sorted by latest first Latest Oldest Best

Back to top | Use Dark Theme