Skip to content

document

The active containment object for layers and all other objects.

The basic canvas for the file.

  • Access the object for the currently active document through Application.activeDocument.
  • You can access other documents or iterate through all open documents using in the Application.documents collection. You can access individual documents in the list by index, or use Documents.getByName() to retrieve them by name.
  • Create documents programmatically using the Documents.add() method.

Document

Bases: Photoshop

The active containment object for the layers and all other objects in the script.

the basic canvas for the file.

Source code in photoshop/api/_document.py
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
class Document(Photoshop):
    """The active containment object for the layers and all other objects in the script.

    the basic canvas for the file.

    """  # noqa: E501

    object_name = "Application"

    def __init__(self, parent):
        super().__init__(parent=parent)
        self._flag_as_method(
            "autoCount",
            "changeMode",
            "close",
            "convertProfile",
            "Flatten",
            "mergeVisibleLayers",
            "crop",
            "export",
            "duplicate",
            "printOneCopy",
            "rasterizeAllLayers",
            "recordMeasurements",
            "revealAll",
            "save",
            "saveAs",
            "splitChannels",
            "trap",
            "trim",
            "resizeImage",
        )

    @property
    def artLayers(self) -> ArtLayers:
        return ArtLayers(self.app.artLayers)

    @property
    def activeLayer(self) -> PS_Layer:
        """The selected layer."""
        type_ = self.eval_javascript("app.activeDocument.activeLayer.typename")
        mappings = {"LayerSet": LayerSet, "ArtLayer": ArtLayer}
        func = mappings[type_]
        return func(self.app.activeLayer)

    @activeLayer.setter
    def activeLayer(self, layer) -> NoReturn:
        """Sets the select layer as active layer.

        Args:
            layer (._artlayer.ArtLayer or
                   ._layerSet.LayerSet): The artLayer.

        """
        self.app.activeLayer = layer

    @property
    def activeChannels(self):
        """The selected channels."""
        return self.app.activeChannels

    @activeChannels.setter
    def activeChannels(self, channels):
        self.app.activeChannels = channels

    @property
    def activeHistoryBrushSource(self):
        """The history state to use with the history brush."""
        return self.app.activeHistoryBrushSource

    @property
    def activeHistoryState(self):
        """The current history state for this document."""
        return self.app.activeHistoryState

    @activeHistoryState.setter
    def activeHistoryState(self, state):
        self.app.activeHistoryState = state

    @property
    def backgroundLayer(self):
        """The background layer for the Document."""
        return self.app.backgroundLayer

    @property
    def bitsPerChannel(self):
        """The number of bits per channel."""
        return self.app.bitsPerChannel

    @bitsPerChannel.setter
    def bitsPerChannel(self, value):
        self.app.bitsPerChannel = value

    @property
    def channels(self):
        return Channels(self.app.channels)

    @property
    def colorProfileName(self):
        """The name of the color profile. Valid only when no value is specified
        for color profile kind (to indicate a custom color profile)."""
        return self.app.colorProfileName

    @colorProfileName.setter
    def colorProfileName(self, name):
        self.app.colorProfileName = name

    @property
    def colorProfileType(self):
        """The type of color model that defines the working space of the
        Document."""
        return self.app.colorProfileType

    @colorProfileType.setter
    def colorProfileType(self, profile_type):
        self.app.colorProfileType = profile_type

    @property
    def colorSamplers(self):
        """The current color samplers associated with the Document."""
        return self.app.colorSamplers

    @property
    def componentChannels(self):
        """The color component channels for this Document."""
        return self.app.componentChannels

    @property
    def countItems(self):
        """The current count items in the Document."""
        return self.app.countItems

    @property
    def fullName(self):
        """The full path name of the Document."""
        try:
            return Path(self.app.fullName)
        except COMError:
            self.eval_javascript(
                'alert ("Please save your Document first!",' '"{}")'.format(self.name),
            )

    @property
    def height(self):
        """The height of the Document."""
        return self.app.Height

    @property
    def histogram(self):
        """A histogram showing the number of pixels at each color intensity
        level for the composite channel."""
        return self.app.Histogram

    @property
    def history_states(self):
        """The history states collection in this Document."""
        return self.app.HistoryStates

    @property
    def id(self):
        """The unique ID of this Document."""
        return self.app.Id

    @property
    def info(self):
        """Metadata about the Document."""
        return DocumentInfo(self.app.info)

    @property
    def layerComps(self):
        """The layer comps collection in this Document."""
        return LayerComps(self.app.layerComps)

    @property
    def layers(self):
        """The layers collection in the Document."""
        return Layers(self.app.Layers)

    @property
    def layerSets(self):
        """The layer sets collection in the Document."""
        return LayerSets(self.app.layerSets)

    @property
    def managed(self):
        """If true, the Document is a workgroup Document."""
        return self.app.Managed

    @property
    def measurement_scale(self):
        """The measurement scale of the Document."""
        return self.app.MeasurementScale

    @property
    def mode(self):
        """The color profile."""
        return self.app.Mode

    @property
    def name(self) -> str:
        """The Document name."""
        return self.app.name

    @property
    def parent(self):
        """The object's container."""
        return self.app.Parent

    @property
    def path(self) -> str:
        """The path to the Document."""
        try:
            return Path(self.app.path)
        except COMError:
            self.eval_javascript(
                'alert ("Please save your Document first!",' '"{}")'.format(self.name),
            )

    @path.setter
    def path(self, path: str) -> NoReturn:
        self.app.fullName = path

    @property
    def pathItems(self):
        return self.app.pathItems

    @property
    def pixelAspectRatio(self):
        """The (custom) pixel aspect ratio of the Document.

        Range: 0.100 to 10.000.

        """
        return self.app.pixelAspectRatio

    @property
    def printSettings(self):
        """Document print settings."""
        return self.app.printSettings

    @property
    def quickMaskMode(self):
        """If true, the document is in Quick Mask mode."""
        return self.app.quickMaskMode

    @property
    def saved(self):
        """If true, the Document been saved since the last change."""
        return self.app.Saved

    @property
    def resolution(self):
        """The resolution of the Document (in pixels per inch)"""
        return self.app.resolution

    @property
    def selection(self):
        """The selected area of the Document."""
        return Selection(self.app.selection)

    @property
    def typename(self):
        """The class name of the object."""
        return self.app.typename

    @property
    def cloudDocument(self):
        """This document is in the cloud."""
        return self.app.cloudDocument

    @property
    def cloudWorkAreaDirectory(self):
        """Local directory for this cloud document."""
        return self.app.cloudWorkAreaDirectory

    @property
    def width(self):
        return self.app.Width

    @property
    def xmpMetadata(self):
        """The XMP properties of the Document. The Camera RAW settings are
        stored here."""
        return self.app.xmpMetadata

    # Methods
    def autoCount(self, *args, **kwargs):
        """Counts the objects in the Document."""
        return self.app.autoCount(*args, **kwargs)

    def changeMode(self, *args, **kwargs):
        """Changes the mode of the Document."""
        return self.app.changeMode(*args, **kwargs)

    def close(self, saving=SaveOptions.DoNotSaveChanges):
        return self.app.close(saving)

    def convertProfile(self):
        return self.app.convertProfile()

    def flatten(self):
        """Flattens all layers."""
        return self.app.Flatten()

    def mergeVisibleLayers(self):
        """Flattens all visible layers in the Document."""
        return self.app.mergeVisibleLayers()

    def crop(
        self,
        bounds: List[int],
        angle: Optional[float] = None,
        width: Optional[int] = None,
        height: Optional[int] = None,
    ):
        """Crops the document.

        Args:
            bounds: Four coordinates for the region remaining after cropping.
            angle: The angle of cropping bounds.
            width: The width of the resulting document.
            height: The height of the resulting document.

        """
        return self.app.crop(bounds, angle, width, height)

    def exportDocument(self, file_path: str, exportAs: ExportType, options: Union[ExportOptionsSaveForWeb]):
        """Exports the Document.

        Note:
          This is a patched version, Due to the problem of dynamic binding,
          we cannot call it directly, so this command is executed by javascript.

        References:
          - https://stackoverflow.com/questions/12286761/saving-a-png-with-photoshop-script-not-working

        """
        file_path = file_path.replace("\\", "/")
        self.app.export(file_path, exportAs, options)

    def duplicate(self, name=None, merge_layers_only=False):
        return Document(self.app.duplicate(name, merge_layers_only))

    def paste(self):
        """Pastes contents of the clipboard into the Document."""
        self.eval_javascript("app.activeDocument.paste()")
        return self.activeLayer

    def print(self):
        """Prints the document."""
        return self.app.print()

    def printOneCopy(self):
        self.app.printOneCopy()

    def rasterizeAllLayers(self):
        return self.app.rasterizeAllLayers()

    def recordMeasurements(self, source, dataPoints):
        """Records the measurements of document."""
        self.app.recordMeasurements(source, dataPoints)

    def reveal_all(self):
        """Expands the Document to show clipped sections."""
        return self.app.revealAll()

    def save(self):
        """Saves the Document."""
        return self.app.save()

    def saveAs(self, file_path, options, asCopy=True, extensionType=ExtensionType.Lowercase):
        """Saves the documents with the specified save options.

        Args:
            file_path (str): Absolute path of psd file.
            options (JPEGSaveOptions): Save options.
            asCopy (bool):
        """
        return self.app.saveAs(file_path, options, asCopy, extensionType)

    def splitChannels(self):
        """Splits the channels of the document."""
        self.app.splitChannels()

    def suspendHistory(self, historyString, javaScriptString):
        """Provides a single history state for the entire script.

        Allows a single undo for all actions taken in the script.

        """
        self.eval_javascript(f"app.activeDocument.suspendHistory('{historyString}', '{javaScriptString}')")

    def trap(self, width: int):
        """
        Applies trapping to a CMYK document.
        Valid only when ‘mode’ = CMYK.

        """
        self.app.trap(width)

    def trim(
        self,
        trim_type: TrimType,
        top: Optional[bool] = True,
        left: Optional[bool] = True,
        bottom: Optional[bool] = True,
        right: Optional[bool] = True,
    ):
        """Trims the transparent area around the image on the specified sides of the canvas.

        Args:
            trim_type: The color or type of pixels to base the trim on.

                Examples:
                    - TrimType.BottomRightPixel
                    - TrimType.TopLeftPixel
                    - TrimType.TransparentPixels

            top: If true, trims away the top of the document.
            left: If true, trims away the left of the document.
            bottom: If true, trims away the bottom of the document.
            right: If true, trims away the right of the document.

        """
        return self.app.trim(trim_type, top, left, bottom, right)

    def resizeImage(self, width: int, height: int, resolution: int = 72, automatic: int = 8):
        """Changes the size of the image.

        Args:
            width: The desired width of the image.
            height: The desired height of the image.
            resolution: The resolution (in pixels per inch)
            automatic: Value for automatic.

        """
        return self.app.resizeImage(width, height, resolution, automatic)

activeChannels property writable

The selected channels.

activeHistoryBrushSource property

The history state to use with the history brush.

activeHistoryState property writable

The current history state for this document.

activeLayer: PS_Layer property writable

The selected layer.

backgroundLayer property

The background layer for the Document.

bitsPerChannel property writable

The number of bits per channel.

cloudDocument property

This document is in the cloud.

cloudWorkAreaDirectory property

Local directory for this cloud document.

colorProfileName property writable

The name of the color profile. Valid only when no value is specified for color profile kind (to indicate a custom color profile).

colorProfileType property writable

The type of color model that defines the working space of the Document.

colorSamplers property

The current color samplers associated with the Document.

componentChannels property

The color component channels for this Document.

countItems property

The current count items in the Document.

fullName property

The full path name of the Document.

height property

The height of the Document.

histogram property

A histogram showing the number of pixels at each color intensity level for the composite channel.

history_states property

The history states collection in this Document.

id property

The unique ID of this Document.

info property

Metadata about the Document.

layerComps property

The layer comps collection in this Document.

layerSets property

The layer sets collection in the Document.

layers property

The layers collection in the Document.

managed property

If true, the Document is a workgroup Document.

measurement_scale property

The measurement scale of the Document.

mode property

The color profile.

name: str property

The Document name.

parent property

The object's container.

path: str property writable

The path to the Document.

pixelAspectRatio property

The (custom) pixel aspect ratio of the Document.

Range: 0.100 to 10.000.

printSettings property

Document print settings.

quickMaskMode property

If true, the document is in Quick Mask mode.

resolution property

The resolution of the Document (in pixels per inch)

saved property

If true, the Document been saved since the last change.

selection property

The selected area of the Document.

typename property

The class name of the object.

xmpMetadata property

The XMP properties of the Document. The Camera RAW settings are stored here.

autoCount(*args, **kwargs)

Counts the objects in the Document.

Source code in photoshop/api/_document.py
336
337
338
def autoCount(self, *args, **kwargs):
    """Counts the objects in the Document."""
    return self.app.autoCount(*args, **kwargs)

changeMode(*args, **kwargs)

Changes the mode of the Document.

Source code in photoshop/api/_document.py
340
341
342
def changeMode(self, *args, **kwargs):
    """Changes the mode of the Document."""
    return self.app.changeMode(*args, **kwargs)

crop(bounds, angle=None, width=None, height=None)

Crops the document.

Parameters:

Name Type Description Default
bounds List[int]

Four coordinates for the region remaining after cropping.

required
angle Optional[float]

The angle of cropping bounds.

None
width Optional[int]

The width of the resulting document.

None
height Optional[int]

The height of the resulting document.

None
Source code in photoshop/api/_document.py
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
def crop(
    self,
    bounds: List[int],
    angle: Optional[float] = None,
    width: Optional[int] = None,
    height: Optional[int] = None,
):
    """Crops the document.

    Args:
        bounds: Four coordinates for the region remaining after cropping.
        angle: The angle of cropping bounds.
        width: The width of the resulting document.
        height: The height of the resulting document.

    """
    return self.app.crop(bounds, angle, width, height)

exportDocument(file_path, exportAs, options)

Exports the Document.

Note

This is a patched version, Due to the problem of dynamic binding, we cannot call it directly, so this command is executed by javascript.

References
Source code in photoshop/api/_document.py
376
377
378
379
380
381
382
383
384
385
386
387
388
def exportDocument(self, file_path: str, exportAs: ExportType, options: Union[ExportOptionsSaveForWeb]):
    """Exports the Document.

    Note:
      This is a patched version, Due to the problem of dynamic binding,
      we cannot call it directly, so this command is executed by javascript.

    References:
      - https://stackoverflow.com/questions/12286761/saving-a-png-with-photoshop-script-not-working

    """
    file_path = file_path.replace("\\", "/")
    self.app.export(file_path, exportAs, options)

flatten()

Flattens all layers.

Source code in photoshop/api/_document.py
350
351
352
def flatten(self):
    """Flattens all layers."""
    return self.app.Flatten()

mergeVisibleLayers()

Flattens all visible layers in the Document.

Source code in photoshop/api/_document.py
354
355
356
def mergeVisibleLayers(self):
    """Flattens all visible layers in the Document."""
    return self.app.mergeVisibleLayers()

paste()

Pastes contents of the clipboard into the Document.

Source code in photoshop/api/_document.py
393
394
395
396
def paste(self):
    """Pastes contents of the clipboard into the Document."""
    self.eval_javascript("app.activeDocument.paste()")
    return self.activeLayer

print()

Prints the document.

Source code in photoshop/api/_document.py
398
399
400
def print(self):
    """Prints the document."""
    return self.app.print()

recordMeasurements(source, dataPoints)

Records the measurements of document.

Source code in photoshop/api/_document.py
408
409
410
def recordMeasurements(self, source, dataPoints):
    """Records the measurements of document."""
    self.app.recordMeasurements(source, dataPoints)

resizeImage(width, height, resolution=72, automatic=8)

Changes the size of the image.

Parameters:

Name Type Description Default
width int

The desired width of the image.

required
height int

The desired height of the image.

required
resolution int

The resolution (in pixels per inch)

72
automatic int

Value for automatic.

8
Source code in photoshop/api/_document.py
476
477
478
479
480
481
482
483
484
485
486
def resizeImage(self, width: int, height: int, resolution: int = 72, automatic: int = 8):
    """Changes the size of the image.

    Args:
        width: The desired width of the image.
        height: The desired height of the image.
        resolution: The resolution (in pixels per inch)
        automatic: Value for automatic.

    """
    return self.app.resizeImage(width, height, resolution, automatic)

reveal_all()

Expands the Document to show clipped sections.

Source code in photoshop/api/_document.py
412
413
414
def reveal_all(self):
    """Expands the Document to show clipped sections."""
    return self.app.revealAll()

save()

Saves the Document.

Source code in photoshop/api/_document.py
416
417
418
def save(self):
    """Saves the Document."""
    return self.app.save()

saveAs(file_path, options, asCopy=True, extensionType=ExtensionType.Lowercase)

Saves the documents with the specified save options.

Parameters:

Name Type Description Default
file_path str

Absolute path of psd file.

required
options JPEGSaveOptions

Save options.

required
asCopy bool
True
Source code in photoshop/api/_document.py
420
421
422
423
424
425
426
427
428
def saveAs(self, file_path, options, asCopy=True, extensionType=ExtensionType.Lowercase):
    """Saves the documents with the specified save options.

    Args:
        file_path (str): Absolute path of psd file.
        options (JPEGSaveOptions): Save options.
        asCopy (bool):
    """
    return self.app.saveAs(file_path, options, asCopy, extensionType)

splitChannels()

Splits the channels of the document.

Source code in photoshop/api/_document.py
430
431
432
def splitChannels(self):
    """Splits the channels of the document."""
    self.app.splitChannels()

suspendHistory(historyString, javaScriptString)

Provides a single history state for the entire script.

Allows a single undo for all actions taken in the script.

Source code in photoshop/api/_document.py
434
435
436
437
438
439
440
def suspendHistory(self, historyString, javaScriptString):
    """Provides a single history state for the entire script.

    Allows a single undo for all actions taken in the script.

    """
    self.eval_javascript(f"app.activeDocument.suspendHistory('{historyString}', '{javaScriptString}')")

trap(width)

Applies trapping to a CMYK document. Valid only when ‘mode’ = CMYK.

Source code in photoshop/api/_document.py
442
443
444
445
446
447
448
def trap(self, width: int):
    """
    Applies trapping to a CMYK document.
    Valid only when ‘mode’ = CMYK.

    """
    self.app.trap(width)

trim(trim_type, top=True, left=True, bottom=True, right=True)

Trims the transparent area around the image on the specified sides of the canvas.

Parameters:

Name Type Description Default
trim_type TrimType

The color or type of pixels to base the trim on.

Examples: - TrimType.BottomRightPixel - TrimType.TopLeftPixel - TrimType.TransparentPixels

required
top Optional[bool]

If true, trims away the top of the document.

True
left Optional[bool]

If true, trims away the left of the document.

True
bottom Optional[bool]

If true, trims away the bottom of the document.

True
right Optional[bool]

If true, trims away the right of the document.

True
Source code in photoshop/api/_document.py
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
def trim(
    self,
    trim_type: TrimType,
    top: Optional[bool] = True,
    left: Optional[bool] = True,
    bottom: Optional[bool] = True,
    right: Optional[bool] = True,
):
    """Trims the transparent area around the image on the specified sides of the canvas.

    Args:
        trim_type: The color or type of pixels to base the trim on.

            Examples:
                - TrimType.BottomRightPixel
                - TrimType.TopLeftPixel
                - TrimType.TransparentPixels

        top: If true, trims away the top of the document.
        left: If true, trims away the left of the document.
        bottom: If true, trims away the bottom of the document.
        right: If true, trims away the right of the document.

    """
    return self.app.trim(trim_type, top, left, bottom, right)

Last update: 2024-03-05
Created: 2024-03-05