[Python] How to Add Editable Text Layer to a Photoshop PSD File using Python

Discussão em 'Python' iniciado por Stack, Maio 5, 2025.

  1. Stack

    Stack Membro Participativo

    I have a very simple use case where I need to pack a PNG file and a text layer into a PSD file and save it. That's it. I have tried psd-tools for it and so far it works in principle.

    The problem is that the text layer that it creates is not editable. The text layer itself is added as an image (transparent background) so I can't edit the text by opening it in Krita/Gimp.

    Here's my code:

    from PIL import Image, ImageDraw, ImageFont
    from psd_tools.api.psd_image import PSDImage
    from psd_tools.api.layers import PixelLayer
    from psd_tools.constants import Compression

    # Load PNG image
    png_image = Image.open('fire.png').convert('RGBA')

    # Create an empty PSD
    psd = PSDImage.new(mode='RGBA', size=png_image.size)

    # Create image layer from PNG
    image_layer = PixelLayer.frompil(
    pil_im=png_image,
    psd_file=psd,
    layer_name='Image Layer',
    compression=Compression.RLE
    )
    psd.append(image_layer)

    # Create a text image with Pillow
    text = "Random Text Example"
    font_size = 40

    try:
    font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", font_size)
    except IOError:
    font = ImageFont.load_default()

    # Create a blank transparent image for the text
    text_image = Image.new("RGBA", png_image.size, (0, 0, 0, 0))
    draw = ImageDraw.Draw(text_image)
    draw.text((50, 50), text, font=font, fill=(255, 0, 0, 255)) # Red text

    # Create text layer from image
    text_layer = PixelLayer.frompil(
    pil_im=text_image,
    psd_file=psd,
    layer_name='Text Layer',
    compression=Compression.RLE
    )
    psd.append(text_layer)

    # Save PSD
    psd.save('output_with_text.psd')


    I have looked other libs and found aspose-psd can do editable text layer, but it's a paid feature in the python library and I need a license for it.

    So, does anybody know a way to add an editable text layer to a PDF file programmatically.? Thanks.

    Continue reading...

Compartilhe esta Página