Photoshop CS6 - Get width of paragraph text in pixels by script
Is there any way to get the width of the text inside a paragraph box? The measurement would not take into account the wrapping. That is, it would equal the sum of each wrapped line.
I'm not asking about the width of the box.
For example, let's say I have a paragraph text containing the string, "!!!!!". In Arial at 12pt, that is 23 px. But if the content were, "mmmmm", the width would be 54px. So the measurement would need to take into account the width of the specific characters in the string.
I can measure that with the ruler tool, but is there a way to get such a measurement in a script?
For Single Lines of Text:
This is a really rinky-dink way of doing it, but you could rasterize the text layer and then measure it:
var artLayerRef = activeDocument.activeLayer; var newLayer = artLayerRef.duplicate(); newLayer.rasterize(RasterizeType.ENTIRELAYER); var width = newLayer.bounds - newLayer.bounds; newLayer.remove(); alert(width);
I clone the layer, rasterize it, get the width, then delete it.
For text that wraps:
Based on the method above, same principle. This is an extremely stupid way of doing it, but I don't see any methods in the scripting reference that would allow you to otherwise easily accomplish this.
Essentially, we're setting the width of the document to the maximum (30,000px) and the same for the text box. If your text is wider than 30,000px then this won't work.
preferences.rulerUnits = Units.PIXELS; var artLayerRef = activeDocument.activeLayer; var originalUnit = preferences.rulerUnits; var docH = activeDocument.height; var docW = activeDocument.width; var newLayer = artLayerRef.duplicate(); var textItem = newLayer.textItem; //It might help if the text box's x coordinate is 0 but shouldn't really matter activeDocument.crop([0, 0, 30000, docH]); // 30000px = maximum width textItem.width = 30000; newLayer.rasterize(RasterizeType.ENTIRELAYER); var width = newLayer.bounds - newLayer.bounds; newLayer.remove(); activeDocument.crop([0, 0, docW, docH]); preferences.rulerUnits = originalUnit; alert(width);