Copy link to clipboard
Copied
How can I rename or save the Photoshop document name using a text later within the document?
I have data coming in from Excel to Photoshop using variables and I need to use that data to rename
the document as well. I thought I had this working at one point but maybe I was doing it a different way.
Is there a way to do it with Scripting? How could this be done?
Thank you!!!
Copy link to clipboard
Copied
This takes the contents of the topmost text layer and renames the file based on that. You'll want to further refine it as this is prety basic.
#target photoshop
renameFromTextLayer();
function renameFromTextLayer(){
try{
if(documents.length > 0){
var originalDialogMode = app.displayDialogs;
app.displayDialogs = DialogModes.ERROR;
var docRef = activeDocument;
var layerText = '';
for(var i = 0; i < docRef.artLayers.length; i++){
var LayerRef = docRef.artLayers[i];
if(LayerRef.kind == LayerKind.TEXT){
layerText = LayerRef.textItem.contents;
break;
}
}
var psFile = File(docRef.fullName);
var psFileName = psFile.name.split('.');
if(psFileName.length > 1){
layerText = layerText + '.' + psFileName[psFileName.length - 1];
}
docRef.close();
psFile.rename(layerText);
}
app.displayDialogs = originalDialogMode;
}
catch(e){
alert(e + e.line);
app.displayDialogs = originalDialogMode;
}
}
Copy link to clipboard
Copied
You can also add code to open the renamed file for it not posible to rename an open document the open document is first closed then its backing file is renamed. I added the open of the renamed file here
#target photoshop
renameFromTextLayer();
function renameFromTextLayer(){
try{
if(documents.length > 0){
var originalDialogMode = app.displayDialogs;
app.displayDialogs = DialogModes.ERROR;
var docRef = activeDocument;
var layerText = '';
for(var i = 0; i < docRef.artLayers.length; i++){
var LayerRef = docRef.artLayers[i];
if( layerText== '' & LayerRef.kind == LayerKind.TEXT){
layerText = LayerRef.textItem.contents;
break;
}
}
if(layerText != ''){
var path = docRef.path + "/";
var psFile = File(docRef.fullName);
var psFileName = psFile.name.split('.');
if(psFileName.length > 1){
layerText = layerText + '.' + psFileName[psFileName.length - 1];
}
var path = docRef.path + "/";
docRef.close();
psFile.rename(layerText);
open(File(path + layerText));
}
else {alert("Not text found")}
}
app.displayDialogs = originalDialogMode;
}
catch(e){
alert(e + e.line);
app.displayDialogs = originalDialogMode;
}
}
Copy link to clipboard
Copied
You would also want to check for an empty text layer, and strip any illegal characters like "/" from the new name, and check to see if a file with that name already exists, and that the file extension is correct. Scripting means you build your own guardrails as you go.
Copy link to clipboard
Copied
JavaScript needs a DoWhatImeanNotWhatIwrote function
Copy link to clipboard
Copied
Excellent points!
On the stripping of illegal characters:
https://prepression.blogspot.com/2019/03/bridge-batch-rename-to-clean-invalid.html
Here is updated CLI code for ExifTool using the same regex to remove anything that is not -_0-9a-zA-Z
exiftool '-FileName<${XMP-photoshop:TextLayerText;tr/-_0-9a-zA-Z//dc}.%e' '/Users/user/Mac OS Path to/Folder-Of-Files-To-Rename'
EDIT – While this version will preserve the original filename (without extension) in XMP metadata before renaming, allowing easy recovery of the original filename using either Adobe Bridge or ExifTool:
exiftool -overwrite_original '-XMP-xmpMM:PreservedFileName<${filename;s/\.[^.]*$//}' -execute '-FileName<${XMP-photoshop:TextLayerText;tr/-_0-9a-zA-Z//dc}.%e' -execute -common_args '/Users/user/Mac OS Path to/Folder-Of-Files-To-Rename'
Copy link to clipboard
Copied
Another option is to use the cross-platform ExifTool CLI utility – however, it all depends on how many text layers there are and in which position the target text layer falls etc.
This example assumes a single text layer and uses the text layer name:
exiftool '-FileName<${XMP-photoshop:TextLayerName}.%e' '/Users/user/Mac OS Path to/Folder-Of-Files-To-Rename'
This example assumes a single text layer and uses the text layer content:
exiftool '-FileName<${XMP-photoshop:TextLayerText}.%e' '/Users/user/Mac OS Path to/Folder-Of-Files-To-Rename'
Windows users would swap the ' single straight quote marks for " double straight quote marks and use an appropriate file system syntax.
Whether using a script or ExifTool command line code, it is probably a good idea to add-in extra code to save the current filename to the XMP-xmpMM:PreservedFileName metadata, just in case you wish to undo the rename and get back to the original filename. One can always use Adobe Bridge Batch Rename Tool to bulk populate the preserved filename metadata into each file, before renaming using another method.
Copy link to clipboard
Copied
Thanks everyone! That helps so much! This works except that when this script is ran in a batch process a dialog box pops up on each photo asking whether to save it or not. I tried to take the "catch" out but it doesn't like that.
Also... I don't know if I should make a new post for this but I'll throw this in here too.
I have a little code here to check the orientation of the active document. Then do an action to rotate it 90 degrees if it is landscape. Two questions on this...
1- How would I do this without using the action? So rotating it with the script?
2- How would it change if I wanted to check and rotate the active layer?
Here is the code for rotating the document.
Thank you!!!
Copy link to clipboard
Copied
If ruler units is set to percent
Copy link to clipboard
Copied
Good observation. I've never had it set to percent though so I'm not worried about that.
But to refrase my question. What is the script for checking a layer to see if it is horizontal, then if it is, rotate it vertical?
Copy link to clipboard
Copied
Layer have bounds that are rectangular like canvases
// enable double-clicking from Mac Finder or Windows Explorer
#target photoshop // this command only works in Photoshop CS2 and higher
// bring application forward for double-click events
app.bringToFront();
// Save the current preferences
var startRulerUnits = app.preferences.rulerUnits;
// Set Photoshop to use pixels
app.preferences.rulerUnits = Units.PIXELS;
try{
var LB = activeDocument.activeLayer.bounds;
var LWidth = (LB[2].value) - (LB[0].value);
var LHeight = (LB[3].value) - (LB[1].value);
MarkX((LB[0].value + LWidth/2));
MarkX(LB[0].value);
MarkX(LB[2].value);
MarkY((LB[1].value + LHeight/2));
MarkY(LB[1].value)
MarkY(LB[3].value)
alert("'" + activeDocument.activeLayer.name + "' Layer Bounds\nTop Left " + LB[0].value + "X," + LB[1].value + "Y Bottom Right " + LB[2].value + "X," + LB[3].value
+ "Y\nWidth " + LWidth + "px Height " + LHeight +"px"
+ "\nLayer center relative to canvas " + (LB[0].value + LWidth/2) + "X," + (LB[1].value + LHeight/2) +"Y"
, "Layer Bounds Info");
}
catch(e){alert("Requires a layer targered");}
// Return the app preferences
app.preferences.rulerUnits = startRulerUnits;
function MarkX(x) {
// =======================================================
var idMk = charIDToTypeID( "Mk " );
var desc61 = new ActionDescriptor();
var idNw = charIDToTypeID( "Nw " );
var desc62 = new ActionDescriptor();
var idPstn = charIDToTypeID( "Pstn" );
var idPxl = charIDToTypeID( "#Pxl" );
desc62.putUnitDouble( idPstn, idPxl, x);
var idOrnt = charIDToTypeID( "Ornt" );
var idOrnt = charIDToTypeID( "Ornt" );
var idVrtc = charIDToTypeID( "Vrtc" );
desc62.putEnumerated( idOrnt, idOrnt, idVrtc );
var idGd = charIDToTypeID( "Gd " );
desc61.putObject( idNw, idGd, desc62 );
executeAction( idMk, desc61, DialogModes.NO );
}
function MarkY(y) {
// =======================================================
var idMk = charIDToTypeID( "Mk " );
var desc63 = new ActionDescriptor();
var idNw = charIDToTypeID( "Nw " );
var desc64 = new ActionDescriptor();
var idPstn = charIDToTypeID( "Pstn" );
var idPxl = charIDToTypeID( "#Pxl" );
desc64.putUnitDouble( idPstn, idPxl, y );
var idOrnt = charIDToTypeID( "Ornt" );
var idOrnt = charIDToTypeID( "Ornt" );
var idHrzn = charIDToTypeID( "Hrzn" );
desc64.putEnumerated( idOrnt, idOrnt, idHrzn );
var idGd = charIDToTypeID( "Gd " );
desc63.putObject( idNw, idGd, desc64 );
executeAction( idMk, desc63, DialogModes.NO );
}
Copy link to clipboard
Copied
You can rotate a layer about any point you want to.
// 2015 John J. McAssey (JJMack)
// ======================================================= */
// This script is supplied as is. It is provided as freeware.
// The author accepts no liability for any problems arising from its use.
// enable double-clicking from Mac Finder or Windows Explorer
#target photoshop // this command only works in Photoshop CS2 and higher
// bring application forward for double-click events
app.bringToFront();
// ensure at least one document open
if (!documents.length) alert('There are no documents open.', 'No Document');
else {
//Set First Time Defaults here
var dfltCpys = 12; // default number of copies including the original
var dfltPos = 4; // default Middle Center
//End Defaults
var Prefs ={}; //Object to hold preferences.
var prefsFile = File(Folder.temp + "/RotateLayerAboutPreferences.dat");
//If preferences do not exit use Defaults from above
if(!prefsFile.exists){
Prefs.Cpys = dfltCpys;
Prefs.Pos = dfltPos;
prefsFile.open('w');
prefsFile.write(Prefs.toSource());
prefsFile.close();
}
else{//Preferences exist so open them
prefsFile.open('r');
Prefs = eval(prefsFile.read());
prefsFile.close();
}
try {
function createDialog(){
// begin dialog layout
var DupRotateDialog = new Window('dialog');
DupRotateDialog.text = 'Duplicate and Rotate Layer';
DupRotateDialog.frameLocation = [78, 100];
DupRotateDialog.alignChildren = 'center';
DupRotateDialog.NumLayerPnl = DupRotateDialog.add('panel', [2, 2, 300, 56], 'Number of Layers and Rotation Anchor Point');
DupRotateDialog.NumLayerPnl.add('statictext', [10, 16, 50, 48], 'Copies ');
DupRotateDialog.NumLayerPnl.imgCpysEdt = DupRotateDialog.NumLayerPnl.add('edittext', [50, 13, 90, 34], Prefs.Cpys, {name:'imgCpys'});
DupRotateDialog.NumLayerPnl.imgCpysEdt.helpTip = 'Number of copies of selected Layer';
DupRotateDialog.NumLayerPnl.add('statictext',[96, 16, 240, 48],'Location');
var position =['Top Left','Top Center','Top Right','Center Left','Center','Center Right','Bottom Left','Bottom Center','Bottom Right','Doc Center','Samples','Path Points'];
DupRotateDialog.NumLayerPnl.dd1 = DupRotateDialog.NumLayerPnl.add('dropdownlist',[150, 13, 260, 34],position);
DupRotateDialog.NumLayerPnl.dd1.selection=Prefs.Pos;
var buttons = DupRotateDialog.add('group');
buttons.orientation = 'row';
var okBtn = buttons.add('button');
okBtn.text = 'OK';
okBtn.properties = {name: 'ok'};
var cancelBtn = buttons.add('button');
cancelBtn.text = 'Cancel';
cancelBtn.properties = {name: 'cancel'};
return DupRotateDialog;
}
dispdlg(createDialog());
function dispdlg(DupRotateDialog){
// display dialog and only continues on OK button press (OK = 1, Cancel = 2)
DupRotateDialog.onShow = function() {
var ww = DupRotateDialog.bounds.width;
var hh = DupRotateDialog.bounds.height;
DupRotateDialog.bounds.x = 78;
DupRotateDialog.bounds.y = 100;
DupRotateDialog.bounds.width = ww;
DupRotateDialog.bounds.height = hh;
}
if (DupRotateDialog.show() == 1) {
//variables passed from user interface
var copies = String(DupRotateDialog.NumLayerPnl.imgCpys.text); if (copies=="") { copies = Prefs.Cpys;}
if (isNaN(copies)) { alert("Non numeric value entered"); dispdlg(createDialog());}
else {
if (copies<2 || copies>360) { alert("Number of layer allow is 2 to 360"); dispdlg(createDialog());} // Not in range
else {
var AnchorPoint = Number(DupRotateDialog.NumLayerPnl.dd1.selection.index) + 1;
cTID = function(s) { return app.charIDToTypeID(s); };
sTID = function(s) { return app.stringIDToTypeID(s); };
// Save the current preferences
Prefs.Cpys = copies;
Prefs.Pos = Number(DupRotateDialog.NumLayerPnl.dd1.selection.index);
prefsFile.open('w');
prefsFile.write(Prefs.toSource());
prefsFile.close();
var startRulerUnits = app.preferences.rulerUnits;
var startTypeUnits = app.preferences.typeUnits;
var startDisplayDialogs = app.displayDialogs;
// Set Photoshop to use pixels and display no dialogs
app.preferences.rulerUnits = Units.PIXELS;
app.preferences.typeUnits = TypeUnits.PIXELS;
app.displayDialogs = DialogModes.NO;
app.togglePalettes();
try { app.activeDocument.suspendHistory('RotateLayerAbout','main(copies, AnchorPoint)' );}
catch(e) {alert(e + ': on line ' + e.line);}
// Return the app preferences
app.togglePalettes();
app.preferences.rulerUnits = startRulerUnits;
app.preferences.typeUnits = startTypeUnits;
app.displayDialogs = startDisplayDialogs;
}
}
}
else {
//alert('Operation Canceled.');
}
}
}
catch(err){
// Lot's of things can go wrong, Give a generic alert and see if they want the details
if ( confirm("Sorry, something major happened and I can't continue! Would you like to see more info?" ) ) { alert(err + ': on line ' + err.line ); }
}
}
function main(stemsAmount, Position) {
if ( Position == 11 && app.activeDocument.colorSamplers.length==0 ) {
alert("No Color Sampler set");
return;
}
if ( Position == 12 ) {
var thePath = selectedPath();
if (thePath == undefined) {
alert("No Path Selected");
return;
}
var myPathInfo = extractSubPathInfo(thePath);
}
// Save selected layer to variable:
var originalStem = app.activeDocument.activeLayer;
// Run the copying process
if(stemsAmount != null){
// Calculate the rotation angle
var angle = 360 / parseInt(stemsAmount);
// Create a group for stems
var stemsGroup = app.activeDocument.layerSets.add();
stemsGroup.name = originalStem.name + " ("+stemsAmount+" stems)";
// Place original layer in group
originalStem.move(stemsGroup, ElementPlacement.INSIDE);
// Duplicate and rotate layers:
for(var i = 1; i < stemsAmount; i++){
// Duplicate original layer and save it to the variable
var newStem = originalStem.duplicate();
// Rotate new layer
switch (Position){
case 1 : newStem.rotate(angle * i, AnchorPosition.TOPLEFT); break;
case 2 : newStem.rotate(angle * i, AnchorPosition.TOPCENTER); break;
case 3 : newStem.rotate(angle * i, AnchorPosition.TOPRIGHT); break;
case 4 : newStem.rotate(angle * i, AnchorPosition.MIDDLELEFT); break;
case 5 : newStem.rotate(angle * i, AnchorPosition.MIDDLECENTER); break;
case 6 : newStem.rotate(angle * i, AnchorPosition.MIDDLERIGHT); break;
case 7 : newStem.rotate(angle * i, AnchorPosition.BOTTOMLEFT); break;
case 8 : newStem.rotate(angle * i, AnchorPosition.BOTTOMCENTER); break;
case 9 : newStem.rotate(angle * i, AnchorPosition.BOTTOMRIGHT); break;
case 10 : app.activeDocument.activeLayer = newStem; rotateAroundPosition(angle * i,activeDocument.width/2,activeDocument.height/2); break;
case 11 : for (var s=0,len=app.activeDocument.colorSamplers.length;s<len;s++) {
if (s!=0) {
// Duplicate original layer and save it to the variable
var newStem = originalStem.duplicate();
}
newStem.name = originalStem.name + " " + (i+1) + " p" + (s+1) ;
app.activeDocument.activeLayer = newStem;
var colorSamplerRef = app.activeDocument.colorSamplers[s];
//alert("angle=" + (angle * i) + " ,x=" + colorSamplerRef.position[0].value + " ,y=" + colorSamplerRef.position[1].value);
rotateAroundPosition(angle * i,colorSamplerRef.position[0].value,colorSamplerRef.position[1].value);
newStem.move(stemsGroup, ElementPlacement.PLACEATEND);
};
break;
case 12 : for(var k=0;k<myPathInfo.length;k++){
for(var j=0;j<myPathInfo[k].entireSubPath.length;j++){
if (k!=0 || j!=0) {
// Duplicate original layer and save it to the variable
var newStem = originalStem.duplicate();
}
newStem.name = originalStem.name + " " + (i+1) + " p" + (j+1) ;
app.activeDocument.activeLayer = newStem;
rotateAroundPosition(angle * i,myPathInfo[k].entireSubPath[j].anchor[0],myPathInfo[k].entireSubPath[j].anchor[1]);
newStem.move(stemsGroup, ElementPlacement.PLACEATEND);
}
}
break;
default : break;
}
// Add index to new layers
if (Position!=11) {
newStem.name = originalStem.name + " " + (i+1);
// Place new layer inside stems group
newStem.move(stemsGroup, ElementPlacement.PLACEATEND);
}
};
// Add index to the original layer
if (Position!=11) originalStem.name += " 1";
else originalStem.name += " 1 p1";
};
activeDocument.activeLayer = activeDocument.layers[0]; // Target top
var groupname = app.activeDocument.activeLayer.name // remember name of group
var idungroupLayersEvent = stringIDToTypeID( "ungroupLayersEvent" ); // this part from Script Listene -- ungroup group
var desc14 = new ActionDescriptor();
var idnull = charIDToTypeID( "null" );
var ref13 = new ActionReference();
var idLyr = charIDToTypeID( "Lyr " );
var idOrdn = charIDToTypeID( "Ordn" );
var idTrgt = charIDToTypeID( "Trgt" );
ref13.putEnumerated( idLyr, idOrdn, idTrgt );
desc14.putReference( idnull, ref13 );
executeAction( idungroupLayersEvent, desc14, DialogModes.NO );
var idMk = charIDToTypeID( "Mk " ); // this part from Script Listene -- group selected layers
var desc15 = new ActionDescriptor();
var idnull = charIDToTypeID( "null" );
var ref14 = new ActionReference();
var idlayerSection = stringIDToTypeID( "layerSection" );
ref14.putClass( idlayerSection );
desc15.putReference( idnull, ref14 );
var idFrom = charIDToTypeID( "From" );
var ref15 = new ActionReference();
var idLyr = charIDToTypeID( "Lyr " );
var idOrdn = charIDToTypeID( "Ordn" );
var idTrgt = charIDToTypeID( "Trgt" );
ref15.putEnumerated( idLyr, idOrdn, idTrgt );
desc15.putReference( idFrom, ref15 );
executeAction( idMk, desc15, DialogModes.NO );
app.activeDocument.activeLayer.name = groupname // recall group name
}
function rotateAroundPosition(_angle,x,y) {
var desc1 = new ActionDescriptor();
var desc2 = new ActionDescriptor();
var ref1 = new ActionReference();
ref1.putEnumerated(charIDToTypeID('Lyr '), charIDToTypeID('Ordn'), charIDToTypeID('Trgt'));
desc1.putReference(charIDToTypeID('null'), ref1);
desc1.putEnumerated(charIDToTypeID('FTcs'), charIDToTypeID('QCSt'), stringIDToTypeID("QCSIndependent"));
desc2.putUnitDouble(charIDToTypeID('Hrzn'), charIDToTypeID('#Pxl'), x);
desc2.putUnitDouble(charIDToTypeID('Vrtc'), charIDToTypeID('#Pxl'), y);
desc1.putObject(charIDToTypeID('Pstn'), charIDToTypeID('Pnt '), desc2);
desc1.putUnitDouble(charIDToTypeID('Angl'), charIDToTypeID('#Ang'), _angle);
desc1.putEnumerated(charIDToTypeID('Intr'), charIDToTypeID('Intp'), charIDToTypeID('Bcbc'));
executeAction(charIDToTypeID('Trnf'), desc1, DialogModes.NO);
}
////// determine selected path //////
function selectedPath () {
try {
var ref = new ActionReference();
ref.putEnumerated( charIDToTypeID("Path"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") );
var desc = executeActionGet(ref);
var theName = desc.getString(charIDToTypeID("PthN"));
return app.activeDocument.pathItems.getByName(theName)
}
catch (e) {
return undefined
}
};
////// michael l hale’s code //////
function extractSubPathInfo(pathObj){
var pathArray = new Array();// each element can be used as the second arugment in pathItems.add ie doc.pathItems.add("myPath1", [pathArray[0]]);
var pl = pathObj.subPathItems.length;
for(var s=0;s<pl;s++){
var pArray = new Array();
for(var i=0;i<pathObj.subPathItems[s].pathPoints.length;i++){
pArray[i] = new PathPointInfo;
pArray[i].kind = pathObj.subPathItems[s].pathPoints[i].kind;
pArray[i].anchor = pathObj.subPathItems[s].pathPoints[i].anchor;
//alert("Anchor " + pathObj.subPathItems[s].pathPoints[i].anchor );
pArray[i].leftDirection = pathObj.subPathItems[s].pathPoints[i].leftDirection;
pArray[i].rightDirection = pathObj.subPathItems[s].pathPoints[i].rightDirection;
};
pathArray[pathArray.length] = new Array();
pathArray[pathArray.length - 1] = new SubPathInfo();
pathArray[pathArray.length - 1].operation = pathObj.subPathItems[s].operation;
pathArray[pathArray.length - 1].closed = pathObj.subPathItems[s].closed;
pathArray[pathArray.length - 1].entireSubPath = pArray;
};
return pathArray;
};
Copy link to clipboard
Copied
Thank you JJMack,
I really appreciate the help, but unfortunately that is way over my head.
I was trying to read through to make sense of it but it looked like there were
a lot of different things going on, and I don't know how to take just the pieces I need.
Sorry for my ignorance.
What I'm looking for is something that works like the document rotation script that I showed as an example (that works perfectly). I tried to adjust it to say "activeLayer" instead of "active.Document" but that didn't work. This is what I changed it to
Error 21: undefined is not an object.
Line: 3
-> if(Layer.width.value>Layer.height.value){//Landscape
I don't really mind how it is rotated because I can build the rest within an action. And
this is all happening within a batch process too so I can't have any dialog boxes popping up on me.
Thanks again!
Copy link to clipboard
Copied
That a look at the Script in my crafting action packages the I wrote to be used in Action. Most are small and well commented. The two plug-in scripts Aspect Ratio Selection and Long Print Side are not simple do not look at those two. Two will Rotate Portrait images to Landscape. One of the two if used twice in an action will rotate the an images rotated on the first run back up. But these rotate the Document not the Layer. You did not post the Rotate Action you script uses the doaction with so I do not know if the Action rotated the active layer or the document.
You woul tehs the layer bounds not the document cancas and rotate the layer if its a layer you want to rotate
app.activeDocument.activeLayer.rotate(90, AnchorPosition.MIDDLECENTER);
Crafting Actions Package UPDATED Aug 10, 2014 Added Conditional Action steps to Action Palette Tips.
Contains
Copy link to clipboard
Copied
So I finally got it to work! For anyone else looking to do this here it is....
This script looks at the active layer, and if it is horizontal, it will rotate the document (and everything in it) vertical.
#target photoshop
{
var LB = activeDocument.activeLayer.bounds;
var LWidth = (LB[2].value) - (LB[0].value);
var LHeight = (LB[3].value) - (LB[1].value);
if (LWidth > LHeight) activeDocument.rotateCanvas(90);
}
Copy link to clipboard
Copied
I do not know why you would want to rotate a document based on some layers aspect ratio. Also if you set your photoshop preferences ruler units to percent you will find your script will not work for width and height will always bet the same 100%.
Here is a script from my crafting action package that rotate portrait images to landscape. You can see how to insure the comparison will work by working with pixels units. The script also checks that there is an active document that can be rotated. The script also save and restores the users ruler units.
/*
<javascriptresource>
<about>$$$/JavaScripts/RotatePortrait/About=JJMack's Rotate Portrait.^r^rCopyright 2009 Mouseprints.^r^rScript utility for action.^rNOTE:Rotate Portrait to Landscape!</about>
<category>JJMack's Action Utility</category>
</javascriptresource>
*/
Rotate();
function Rotate() {
// validate that a document is open
if (documents.length < 1) {
alert("No Open Document!");
return;
}
var orig_ruler_units = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
// Rotate portrait to landscape orientation
if (activeDocument.height > activeDocument.width) activeDocument.rotateCanvas(90);
// Reset units to original settings
app.preferences.rulerUnits = orig_ruler_units;
}