2013-01-04

Sample Python script to control Photoshop

I have been using Python to script Photoshop and came across something that wasn’t immediately obvious to me:

A sample section would be:

// Create a new 2x4 inch document and assign it to a variable
var docRef = app.documents.add( 250, 33 )

which I got to work as:

# Create a new 2x4 inch document and assign it to a variable.
docs = psApp.Documents
docRef = docs.Add(250,33)

you are not able to two level of indirection on COM objects but keep need to making Python objects of the references.

The complete sample code is:

import win32com.client

psApp = win32com.client.Dispatch("Photoshop.Application")

# Remember current unit settings and then set units to
# the value expected by this script
originalRulerUnits = psApp.Preferences.RulerUnits
psApp.Preferences.RulerUnits = 1 # 1= psPixesl, 2 = inches

# Create a new 2x4 inch document and assign it to a variable.
docs = psApp.Documents
docRef = docs.Add(250,33)

# Create a new art layer containing text
layers = docRef.artLayers
artLayerRef = layers.add

artLayerRef.kind = 2 #Text layer
# Set the contents of the text layer.
textItemRef = artLayerRef.TextItem
textItemRef.Contents = "Hello, Web!"

# Restore unit setting
psApp.Preferences.RulerUnits = originalRulerUnits

No comments: