Sub topic 15
Creating and styling text layers with a script
This chapter shows how to create and style Photoshop text layers from code. It assumes you can already do the same work by hand with the Type tool, the Character panel and the Paragraph panel. It also assumes basic JavaScript (functions, objects, try/catch). The scripts use ExtendScript, the JavaScript dialect built into Photoshop, and run from File > Scripts > Browse.... Photoshop's newer UXP plugin system uses a different API, and none of this chapter's code applies to it.
The object model behind a type layer
A text layer is an ArtLayer whose kind is LayerKind.TEXT. All text settings live on its textItem property. Each property matches a control you already know from the panels.
| Panel control | `textItem` property | Value type |
|---|---|---|
| Text content | `contents` | String (`"\r"` starts a new paragraph) |
| Font family and style | `font` | PostScript name, such as `"ArialMT"` |
| Size | `size` | `UnitValue` |
| Color | `color` | `SolidColor` |
| Leading | `useAutoLeading`, `leading` | Boolean, `UnitValue` |
| Tracking | `tracking` | Number, in 1/1000 em |
| Kerning mode | `autoKerning` | `AutoKernType` constant |
| Baseline shift | `baselineShift` | `UnitValue` |
| Alignment | `justification` | `Justification` constant |
| Indents and spacing | `firstLineIndent`, `leftIndent`, `rightIndent`, `spaceBefore`, `spaceAfter` | `UnitValue` |
| Point or paragraph text | `kind` | `TextType` constant |
| Box size | `width`, `height` | `UnitValue` |
| Anti-aliasing | `antiAliasMethod` | `AntiAlias` constant |
Control units before you write values
Many properties accept a UnitValue, which pairs a number with a unit. A plain number is read in the unit that Photoshop's preferences currently select. That makes a script behave differently on a machine with different preferences. Set the units at the start of the script and restore them at the end.
#target photoshop
var oldRuler = app.preferences.rulerUnits;
var oldType = app.preferences.typeUnits;
app.preferences.rulerUnits = Units.PIXELS;
app.preferences.typeUnits = TypeUnits.POINTS;
try {
// ... your work here ...
} finally {
app.preferences.rulerUnits = oldRuler;
app.preferences.typeUnits = oldType;
}The finally block restores the preferences even when the script fails partway.
Check that a font exists
The font property takes a PostScript name, not the menu name you see in the Character panel. Arial Regular is "ArialMT" and Arial Bold is "Arial-BoldMT". A name Photoshop does not recognize raises an error. Check the installed fonts first so you can fall back to a safe choice.
#target photoshop
function hasFont(postScriptName) {
for (var i = 0; i < app.fonts.length; i++) {
if (app.fonts[i].postScriptName === postScriptName) {
return true;
}
}
return false;
}
// Print every installed font as "Menu Name -> PostScriptName"
var lines = [];
for (var i = 0; i < app.fonts.length; i++) {
lines.push(app.fonts[i].name + " -> " + app.fonts[i].postScriptName);
}
$.writeln(lines.join("\n"));
$.writeln("ArialMT installed: " + hasFont("ArialMT"));Output from $.writeln appears in the ExtendScript Toolkit console or VS Code's ExtendScript debugger. To see the output without those tools, pass the string to alert() instead.
A reusable text-layer function
Repeating the same eight lines for every label is error-prone. Put the work in one function that takes an options object. The version below handles point text and paragraph text, and it falls back to a default font if the requested one is missing.
#target photoshop
function makeColor(r, g, b) {
var c = new SolidColor();
c.rgb.red = r;
c.rgb.green = g;
c.rgb.blue = b;
return c;
}
function hasFont(postScriptName) {
for (var i = 0; i < app.fonts.length; i++) {
if (app.fonts[i].postScriptName === postScriptName) {
return true;
}
}
return false;
}
function addTextLayer(doc, opts) {
var layer = doc.artLayers.add();
layer.kind = LayerKind.TEXT;
layer.name = opts.name;
var item = layer.textItem;
// Switch to paragraph text BEFORE setting width and height.
if (opts.box) {
item.kind = TextType.PARAGRAPHTEXT;
item.width = new UnitValue(opts.box.w, "px");
item.height = new UnitValue(opts.box.h, "px");
}
item.contents = opts.text;
item.font = hasFont(opts.font) ? opts.font : "ArialMT";
item.size = new UnitValue(opts.size, "pt");
item.color = opts.color;
if (opts.leading) {
item.useAutoLeading = false;
item.leading = new UnitValue(opts.leading, "pt");
}
if (opts.tracking !== undefined) {
item.tracking = opts.tracking;
}
if (opts.justification) {
item.justification = opts.justification;
}
item.position = [new UnitValue(opts.x, "px"), new UnitValue(opts.y, "px")];
return layer;
}
function main() {
if (app.documents.length === 0) {
alert("Open a document first.");
return;
}
var doc = app.activeDocument;
var oldRuler = app.preferences.rulerUnits;
var oldType = app.preferences.typeUnits;
app.preferences.rulerUnits = Units.PIXELS;
app.preferences.typeUnits = TypeUnits.POINTS;
try {
addTextLayer(doc, {
name: "Headline",
text: "Spring Sale",
font: "Arial-BoldMT",
size: 54,
color: makeColor(30, 30, 120),
tracking: 20,
x: 80,
y: 160
});
addTextLayer(doc, {
name: "Body",
text: "Save on every item in the store.\rOffer ends Sunday.",
font: "ArialMT",
size: 18,
color: makeColor(40, 40, 40),
leading: 26,
justification: Justification.LEFT,
box: { w: 420, h: 160 },
x: 80,
y: 220
});
} finally {
app.preferences.rulerUnits = oldRuler;
app.preferences.typeUnits = oldType;
}
}
// One History entry, so a single Undo removes both layers.
app.activeDocument.suspendHistory("Add text layers", "main()");Several points in this script are worth understanding:
- Order of operations.
widthandheightonly exist on paragraph text. Setting them on point text raises an error, so the script changeskindfirst. - Position meaning. For point text,
positionis the left end of the baseline, not the top-left corner. For paragraph text it is the top-left corner of the box. - Paragraph breaks. Photoshop uses
"\r"as the paragraph separator. A"\n"may show up as a stray character or fail to break the line. - Leading.
leadinghas no effect whileuseAutoLeadingistrue, so the script turns auto leading off first. - History.
suspendHistorygroups everything into one undo step. Without it, each property change adds its own entry and floods the History panel.
Limits of the textItem object
The textItem object applies one set of formatting to the whole layer. The DOM has no property for styling a single word, such as bolding one word in a sentence. The usual workaround is to record the action with the ScriptListener plug-in and replay the generated Action Manager code (executeAction, ActionDescriptor). That code is verbose and fragile across Photoshop versions. If you only need uniform formatting, stay with textItem. If you need mixed formatting, consider two layers or a character style applied by hand.
Scripts also cannot reliably create or apply Character and Paragraph styles through the standard DOM. Configure the look in the script instead, or apply styles manually after the script runs.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| "General Photoshop error" when setting `font` | Name is not a PostScript name, or the font is not installed | Check with `app.fonts` first |
| Error when setting `width` | Layer is still point text | Set `kind = TextType.PARAGRAPHTEXT` first |
| Text is tiny or huge | Unit preferences differ from your assumptions | Use `UnitValue` and set `typeUnits` |
| Leading stays the same | `useAutoLeading` is still `true` | Set it to `false` before `leading` |
| Text lands in the wrong place | Baseline origin versus box corner | Check the text kind, then adjust `position` |
| `activeDocument` error | No open document | Test `app.documents.length` |
Exercise
A script sets item.width = new UnitValue(300, "px") on a layer created with layer.kind = LayerKind.TEXT and gets an error. What is missing, and where in the script must the fix go?
Show answer
The layer is still point text, which has no fixed box. Set item.kind = TextType.PARAGRAPHTEXT before setting width and height.
Exercise
You set item.leading = new UnitValue(30, "pt") but the line spacing does not change. Which property do you set first, and to what value?
Show answer
Set item.useAutoLeading = false. While auto leading is on, Photoshop ignores the leading value.
Exercise
Extend addTextLayer so it accepts an optional opts.justification of Justification.CENTER and creates a centered caption inside a 600 by 100 pixel box at position (60, 500). Write the call.
Show answer
addTextLayer(doc, { name: "Caption", text: "Figure 1", font: "ArialMT", size: 14, color: makeColor(90, 90, 90), justification: Justification.CENTER, box: { w: 600, h: 100 }, x: 60, y: 500 });