Skip to main content
dendenis82
Inspiring
October 13, 2024
Answered

Use text from clipboard as filename during Save As.

  • October 13, 2024
  • 4 replies
  • 1882 views

HI!
I can't save as file with text from clipboard to path. I noticed that one of gpt used approach asking powershell by get-clipboard command. But I have alert: "Clipboard is empty or inaccessible". After this I checked clipboard in powershell with mentioned command and it's returns my text stored in clipboard; Any help, please.

 

#target photoshop

function getClipboardText() {
    var clipText = "";
    try {
        var tempFile = new File("~/Desktop/temp_clipboard.txt");
        app.system("powershell -command Get-Clipboard > \"" + tempFile.fsName + "\"");
        
        // Open the temporary file to read clipboard content
        tempFile.open('r');
        clipText = tempFile.read();
        tempFile.close();
        
        // Remove the temporary file
        tempFile.remove();
    } catch (e) {
        alert("Error accessing clipboard: " + e.message);
    }
    return clipText ? clipText.trim() : ""; // Return trimmed text or empty string
}

if (app.documents.length > 0) {
    var doc = app.activeDocument;
    var clipboardText = getClipboardText();
    
    if (clipboardText !== "") {
        var saveFile = new File("C:\\Desktop\\Art4CNC\\" + clipboardText + ".psb");

        var psbSaveOptions = new PhotoshopSaveOptions();
        psbSaveOptions.alphaChannels = true;
        psbSaveOptions.annotations = true;
        psbSaveOptions.embedColorProfile = true;
        psbSaveOptions.layers = true;
        psbSaveOptions.spotColors = true;

        try {
            doc.saveAs(saveFile, psbSaveOptions, true, Extension.LOWERCASE);
            alert("File saved as " + clipboardText + ".psb in C:\\Desktop\\Art4CNC\\");
        } catch (e) {
            alert("Error saving file: " + e.message);
        }
    } else {
        alert("Clipboard is empty or inaccessible.");
    }
} else {
    alert("No open documents to save.");
}

 

 

 

 

[scripting topic added by moderator]

 

 

 

This topic has been closed for replies.
Correct answer dendenis82

Thank you guys,
Ended up with this one, works fine: it takes clipboard and name with it an open document without any interruption.
Updated: it's .jsx script that creates .bat file and Clipboard file and then delete them. 

 

//  The script will seamlessly save open document as ClipboardText.psb in the same directory;
//  known issues: cyrillic characters will result in underscore.
 
// Function to execute a command
function executeCommand(command) {
    var fileObj = new File(command);
    fileObj.execute();
}

try {
    // Get the directory of the current document
    var doc = app.activeDocument;
    var docPath = doc.path;

    // Define the batch file path and clipboard file path
    var tempBatchFile = new File(docPath + "/TempClipboard.bat");
    var clipboardFilePath = docPath + "/Clipboard.txt";

    // Create the batch script
    tempBatchFile.open("w");
    tempBatchFile.writeln("@echo off");
    tempBatchFile.writeln(":: Get the directory where the batch file is located");
    tempBatchFile.writeln("set \"batchDir=%~dp0\"");
    tempBatchFile.writeln(":: Save clipboard content to Clipboard.txt in the same directory");
    tempBatchFile.writeln("powershell -command \"& {Get-Clipboard | Out-File -FilePath '%batchDir%Clipboard.txt' -Encoding UTF8}\"");
    tempBatchFile.close();

    // Execute the Batch script to create Clipboard.txt
    executeCommand(tempBatchFile.fsName);

    // Wait for the batch file to complete
    $.sleep(1000);

    // Remove the temporary batch file
    tempBatchFile.remove();

    // Read the text content from Clipboard.txt
    var inputFile = new File(clipboardFilePath);
    inputFile.open("r"); // Open the file in read mode
    // inputFile.open("r",'e', 'TEXT', '????');
    var fileName = inputFile.read(); // Read the file content as is
    inputFile.close();
    inputFile.remove(); // Optionally delete the clipboard file

    // Trim leading and trailing spaces
    fileName = fileName.replace(/^\s+|\s+$/g, ""); // Remove leading and trailing whitespace

    // Sanitize filename: Replace invalid characters, replace spaces, and limit characters
    fileName = fileName.replace(/[\/\\:*?"<>|]/g, "_"); // Replace invalid characters
    fileName = fileName.replace(/\s+/g, "_"); // Replace spaces with underscores
    fileName = fileName.substring(0, 60); // Limit characters to 60

    // Create the save file path with .psb extension
    var saveFile = new File(docPath + "/" + fileName + ".psb");

    // Function to save as PSB with specified options
    function saveAsPSB(thePath, asCopy, theDialog) {
        var s2t = function (s) {
            return app.stringIDToTypeID(s);
        };
        var descriptor = new ActionDescriptor();
        var descriptor2 = new ActionDescriptor();
        descriptor.putObject(s2t("as"), s2t("largeDocumentFormat"), descriptor2); // Specify PSB format
        descriptor.putPath(s2t("in"), thePath); // Specify save path
        descriptor.putBoolean(s2t("copy"), asCopy); // Save as a copy if true
        descriptor.putBoolean(s2t("lowerCase"), true); // Use lowercase extension
        descriptor.putBoolean(s2t("layers"), true); // Save with layers
        descriptor.putBoolean(s2t("alphaChannels"), true); // Save with alpha channels
        descriptor.putBoolean(s2t("maximizeCompatibility"), false); // Don't maximize compatibility
        descriptor.putBoolean(s2t("embedProfile"), true); // Embed color profile

        executeAction(s2t("save"), descriptor, theDialog); // Execute the save action
    }

    // Save the document strictly as PSB
    saveAsPSB(saveFile, false, DialogModes.NO);

} catch (e) {
    // Minimal error handling for unexpected issues
    alert("Error: " + e.message);
}

 

 

 

 

 

 

 

 

 

4 replies

dendenis82
dendenis82AuthorCorrect answer
Inspiring
November 30, 2024

Thank you guys,
Ended up with this one, works fine: it takes clipboard and name with it an open document without any interruption.
Updated: it's .jsx script that creates .bat file and Clipboard file and then delete them. 

 

//  The script will seamlessly save open document as ClipboardText.psb in the same directory;
//  known issues: cyrillic characters will result in underscore.
 
// Function to execute a command
function executeCommand(command) {
    var fileObj = new File(command);
    fileObj.execute();
}

try {
    // Get the directory of the current document
    var doc = app.activeDocument;
    var docPath = doc.path;

    // Define the batch file path and clipboard file path
    var tempBatchFile = new File(docPath + "/TempClipboard.bat");
    var clipboardFilePath = docPath + "/Clipboard.txt";

    // Create the batch script
    tempBatchFile.open("w");
    tempBatchFile.writeln("@echo off");
    tempBatchFile.writeln(":: Get the directory where the batch file is located");
    tempBatchFile.writeln("set \"batchDir=%~dp0\"");
    tempBatchFile.writeln(":: Save clipboard content to Clipboard.txt in the same directory");
    tempBatchFile.writeln("powershell -command \"& {Get-Clipboard | Out-File -FilePath '%batchDir%Clipboard.txt' -Encoding UTF8}\"");
    tempBatchFile.close();

    // Execute the Batch script to create Clipboard.txt
    executeCommand(tempBatchFile.fsName);

    // Wait for the batch file to complete
    $.sleep(1000);

    // Remove the temporary batch file
    tempBatchFile.remove();

    // Read the text content from Clipboard.txt
    var inputFile = new File(clipboardFilePath);
    inputFile.open("r"); // Open the file in read mode
    // inputFile.open("r",'e', 'TEXT', '????');
    var fileName = inputFile.read(); // Read the file content as is
    inputFile.close();
    inputFile.remove(); // Optionally delete the clipboard file

    // Trim leading and trailing spaces
    fileName = fileName.replace(/^\s+|\s+$/g, ""); // Remove leading and trailing whitespace

    // Sanitize filename: Replace invalid characters, replace spaces, and limit characters
    fileName = fileName.replace(/[\/\\:*?"<>|]/g, "_"); // Replace invalid characters
    fileName = fileName.replace(/\s+/g, "_"); // Replace spaces with underscores
    fileName = fileName.substring(0, 60); // Limit characters to 60

    // Create the save file path with .psb extension
    var saveFile = new File(docPath + "/" + fileName + ".psb");

    // Function to save as PSB with specified options
    function saveAsPSB(thePath, asCopy, theDialog) {
        var s2t = function (s) {
            return app.stringIDToTypeID(s);
        };
        var descriptor = new ActionDescriptor();
        var descriptor2 = new ActionDescriptor();
        descriptor.putObject(s2t("as"), s2t("largeDocumentFormat"), descriptor2); // Specify PSB format
        descriptor.putPath(s2t("in"), thePath); // Specify save path
        descriptor.putBoolean(s2t("copy"), asCopy); // Save as a copy if true
        descriptor.putBoolean(s2t("lowerCase"), true); // Use lowercase extension
        descriptor.putBoolean(s2t("layers"), true); // Save with layers
        descriptor.putBoolean(s2t("alphaChannels"), true); // Save with alpha channels
        descriptor.putBoolean(s2t("maximizeCompatibility"), false); // Don't maximize compatibility
        descriptor.putBoolean(s2t("embedProfile"), true); // Embed color profile

        executeAction(s2t("save"), descriptor, theDialog); // Execute the save action
    }

    // Save the document strictly as PSB
    saveAsPSB(saveFile, false, DialogModes.NO);

} catch (e) {
    // Minimal error handling for unexpected issues
    alert("Error: " + e.message);
}

 

 

 

 

 

 

 

 

 

dendenis82
Inspiring
November 30, 2024

But still with minor issue: I need .psb file. Current open document is also .psb file. 
But script won't save it as psb. It's saves as psd even when file size is over 2gb.

Legend
December 1, 2024

Thank you, it works now!
I've updated posted script with it.


quote

I've updated posted script with it.

By @dendenis82

 

There  are a few more parameters that can be passed in the descriptor. If they are missing, they take some default values. You may want to control some of them.

 

UPD. Also, the bat (cmd) file does not need to be stored separately You can create it in a temporary folder using your script, then run it and then delete it.

Legend
November 30, 2024

Write your command in a bat file and run it instead of app.system() like here .

Legend
October 14, 2024

Adobe has zero support for Powershell code. There is a workaround that I use involving writing a temp file and executing it with Windows Scripting Host but its a kludge at best.

You can create a temp document or add a text layer to your existing document, paste, copy the textitem, and delete your temp file/layer.

dendenis82
Inspiring
November 30, 2024

Seems like Photoshop can't name layer with clipboard text via script: it's returns error "clipboard is empty of inaccessible", despite I can name layer with text from clipboard manually via Ctrl+V while editing layer name.

Stephen Marsh
Community Expert
Community Expert
November 30, 2024

This is why I previously asked how the text gets in the clipboard – what are the workflow steps? Could the workflow be adjusted to work within the constraints of scripting?

Stephen Marsh
Community Expert
Community Expert
October 13, 2024

You can find cross-platform ExtendScript code for text to clipboard in these topics: