Photoshop JS specify font - javascript

I'm trying to modify a script to work for what I need it to do and keep getting the "TypeError: undefined is not an object ... I can't figure out why though. I've copy and pasted pretty much everything. The problem line as setting the font to Adobe Garamond.
Script listener has these lines that I think are related but, I don't know JS enough to get it.
var idfontPostScriptName = stringIDToTypeID( "fontPostScriptName" );
desc22.putString( idfontPostScriptName, """AGaramondPro-Regular""" );
var idFntN = charIDToTypeID( "FntN" );
desc22.putString( idFntN, """Adobe Garamond Pro""" );
var idFntS = charIDToTypeID( "FntS" );
desc22.putString( idFntS, """Regular""" );
My script looks like
// this script is a variation of the script addTimeStamp.js that is installed with PH7
//OPENED document has size
if ( documents.length > 0 )
{
var originalDialogMode = app.displayDialogs;
app.displayDialogs = DialogModes.ERROR;
var originalRulerUnits = preferences.rulerUnits;
preferences.rulerUnits = Units.PIXELS;
try
{
var docRef = activeDocument;
// Now create a text layer at the front
var myLayerRef = docRef.artLayers.add();
myLayerRef.kind = LayerKind.TEXT;
myLayerRef.name = "Filename";
var myTextRef = myLayerRef.textItem;
// strip the extension off
var fileNameNoExtension = docRef.name;
fileNameNoExtension = fileNameNoExtension.split( "." );
if ( fileNameNoExtension.length > 1 ) {
fileNameNoExtension.length--;
}
fileNameNoExtension = fileNameNoExtension.join(".");
myTextRef.contents = fileNameNoExtension;
// off set the text to be in the middle
myTextRef.position = new Array( docRef.width / 2, docRef.height / 2 );
myTextRef.size = 135;
myTextRef.textItem.font = 'AGaramondPro-Regular';
}
catch( e )
{
// An error occurred. Restore ruler units, then propagate the error back
// to the user
preferences.rulerUnits = originalRulerUnits;
app.displayDialogs = originalDialogMode;
throw e;
}
// Everything went Ok. Restore ruler units
preferences.rulerUnits = originalRulerUnits;
app.displayDialogs = originalDialogMode;
}
else
{
alert( "You must have a document open to add the filename!" );
}

Oh my hell. Just answered my own question again. Sorry guys.
myTextRef.font = 'AGaramondPro-Regular';

Related

Photoshop javascript batch replace smart layer from folder and resize

I am trying to work out how to use javascript with photoshop, but eventhough i dont find a logical error in the code, it doesnt work properly.
I have a folder of 1000+ images/.ai files that have varying dimensions. I need these images on the Pillow and saved as .jpeg.
I choose the smartlayer and run the script to choose the images and it saves them correctly. The only problem is, that the resizing of images and positioning dont work properly.
If i put the image in manually, it works without issues, but not with the script.
If the width is greater than the height, it should set the width to 1200 px and calculate the height according to that. (and vice versa) and place in the middle of the layer.
How do i fix the resizing and positioning?
Is it possible to choose a folder where the images are inside instead of selecting the images?
How do i handle it when there are 2 smart layers to change in the mockup instead of 1?
Anyone know where the problem lies this code?
Im grateful for any bit of help!
// Replace SmartObject’s Content and Save as JPG
// 2017, use it at your own risk
// Via #Circle B: https://graphicdesign.stackexchange.com/questions/92796/replacing-a-smart-object-in-bulk-with-photoshops-variable-data-or-scripts/93359
// JPG code from here: https://forums.adobe.com/thread/737789
#target photoshop
if (app.documents.length > 0) {
var myDocument = app.activeDocument;
var theName = myDocument.name.match(/(.*)\.[^\.]+$/)[1];
var thePath = myDocument.path;
var theLayer = myDocument.activeLayer;
// JPG Options;
jpgSaveOptions = new JPEGSaveOptions();
jpgSaveOptions.embedColorProfile = true;
jpgSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
jpgSaveOptions.matte = MatteType.NONE;
jpgSaveOptions.quality = 8;
// Check if layer is SmartObject;
if (theLayer.kind != "LayerKind.SMARTOBJECT") {
alert("selected layer is not a smart object")
} else {
// Select Files;
if ($.os.search(/windows/i) != -1) {
var theFiles = File.openDialog("please select files", "*.psd;*.tif;*.jpg;*.ai", true)
} else {
var theFiles = File.openDialog("please select files", getFiles, true)
};
};
(function (){
var startRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
var bounds = activeDocument.activeLayer.bounds;
var height = bounds[3].value - bounds[1].value;
var width = bounds[2].value - bounds[0].value;
if (height > width){
var newSize1 = (100 / width) * 800;
activeDocument.activeLayer.resize(newSize1, newSize1, AnchorPosition.MIDDLECENTER);
app.preferences.rulerUnits = startRulerUnits;
}
else{
var newSize2 = (100 / height) * 800;
activeDocument.activeLayer.resize(newSize2, newSize2, AnchorPosition.MIDDLECENTER);
app.preferences.rulerUnits = startRulerUnits;
}
})();
if (theFiles) {
for (var m = 0; m < theFiles.length; m++) {
// Replace SmartObject
theLayer = replaceContents(theFiles[m], theLayer);
var theNewName = theFiles[m].name.match(/(.*)\.[^\.]+$/)[1];
// Save JPG
myDocument.saveAs((new File(thePath + "/" + theName + "_" + theNewName + ".jpg")), jpgSaveOptions, true,Extension.LOWERCASE);
}
}
};
// Get PSDs, TIFs and JPGs from files
function getFiles(theFile) {
if (theFile.name.match(/\.(psd|tif|jpg)$/i) != null || theFile.constructor.name == "Folder") {
return true
}
};
// Replace SmartObject Contents
function replaceContents(newFile, theSO) {
app.activeDocument.activeLayer = theSO;
// =======================================================
var idplacedLayerReplaceContents = stringIDToTypeID("placedLayerReplaceContents");
var desc3 = new ActionDescriptor();
var idnull = charIDToTypeID("null");
desc3.putPath(idnull, new File(newFile));
var idPgNm = charIDToTypeID("PgNm");
desc3.putInteger(idPgNm, 1);
executeAction(idplacedLayerReplaceContents, desc3, DialogModes.NO);
return app.activeDocument.activeLayer
};
I have attached 2 pictures. 1 how it needs to look like and 2 what the script outputs
Correct
Wrong
Your replaced images have to be the same resolution as the smart object.
You can declare the folder path in your code. If you still want to select the path by hand, you can select one image in the path, and extract the parent folder path.
You can recursively go through all of the layers in the documents and extract all the smart objects that you want to replace.
You may want a function to recursively traverse all the layers in the document
function browseLayer(layer, fn) {
if (layer.length) {
for (var i = 0; i < layer.length; ++i) {
browseLayer(layer[i], fn)
}
return;
}
if (layer.layers) {
for (var j = 0; j < layer.layers.length; ++j) {
browseLayer(layer.layers[j], fn);
}
return;
}
//apply this function for every layer
fn(layer)
}
Get all the smart objects in the document
const smartObjects = [];
//The smart objects can be visit twice or more
//use this object to mark the visiting status
const docNameIndex = {};
const doc = app.open(new File("/path/to/psd/file"));
browseLayer(doc.layers, function (layer) {
//You cannot replace smart object with position is locked
if (layer.kind == LayerKind.SMARTOBJECT && layer.positionLocked == false) {
smartLayers.push(layer);
doc.activeLayer = layer;
//open the smart object
executeAction(stringIDToTypeID("placedLayerEditContents"), new ActionDescriptor(), DialogModes.NO);
//activeDocument is now the smart object
const docName = app.activeDocument.name;
if (!docNameIndex[docName]) {
docNameIndex[docName] = true;
smartObjects.push({
id: layer.id,
name: layer.name,
docName: docName,
width : app.activeDocument.width.as('pixels'),
height : app.activeDocument.height.as('pixels'),
resolution : app.activeDocument.resolution //important
});
}
//reactive the main document
app.activeDocument = doc;
}
});
I assume that you have two smart objects needed to replace, the images for replacement are stored in different folders with the same name.
smartObjects[0].replaceFolderPath = "/path/to/folder/1";
smartObjects[1].replaceFolderPath = "/path/to/folder/2";
//we need temp folder to store the resize images
smartObjects[0].tempFolderPath = "/path/to/temp/folder/1";
smartObjects[1].tempFolderPath = "/path/to/temp/folder/2";
Ex: The first iteration will replace smartObjects[0] with "/path/to/folder/1/image1.jpg", and smartObjects[1] with "/path/to/folder/image1.jpg"
Now resize all the images following the properties of the smart objects
smartObjects.forEach(function(smartObject){
//Get all files in the folder
var files = new Folder(smartObject.replaceFolderPath).getFiles();
//Resize all the image files
files.forEach(function (file) {
var doc = app.open(file);
doc.resizeImage(
new UnitValue(smartObject.width + ' pixels'),
new UnitValue(smartObject.height + ' pixels'),
smartObject.resolution
);
//save to temp folder
doc.saveAs(
new File(smartObject.tempFolderPath + "/" + file.name),
new PNGSaveOptions(),
true
);
doc.close(SaveOptions.DONOTSAVECHANGES)
});
});
Finally, replace the smart object
//get list of file again
var files = new Folder(smartObject.replaceFolderPath).getFiles();
files.forEach(function(file){
var fileName = file.name;
smartObjects.forEach(function(smartObject){
//active the window opening the smart object
app.activeDocument = app.documents.getByName(args.documentName);
var desc = new ActionDescriptor();
desc.putPath(charIDToTypeID("null"), new File(smartObject.tempFolderPath + "/" + fileName));
executeAction(stringIDToTypeID( "placedLayerReplaceContents" ), desc, DialogModes.NO);
});
//Now export document
var webOptions = new ExportOptionsSaveForWeb();
webOptions.format = SaveDocumentType.PNG; // SaveDocumentType.JPEG
webOptions.optimized = true;
webOptions.quality = 100;
doc.exportDocument(new File("/path/to/result/folder" + file.name), ExportType.SAVEFORWEB, webOptions);
});
Now you can close all the opening smart objects
smartObjects.forEach(function (s) {
app.documents.getByName(r.docName).close(SaveOptions.DONOTSAVECHANGES);
});

How to use Adobe Illustrator Scripting for Artboard?

I'm trying to load my SVG-images as layers folder onto a current document. Somehow I'm able to manage it for new document by using the script below but what I need is that I want to import all my images to current opened document. Can someone suggest how I can change the script below for doing this task?
Script source code is:
function getFolder() {
return Folder.selectDialog('Please select the folder to be imported:', Folder('~'));
}
function importFolderAsLayers(selectedFolder) {
// if a folder was selected continue with action, otherwise quit
var document;
var mm = 2.83464567; // Metric MM converter…
// Set the script to work with artboard rulers
app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM;
if (selectedFolder) {
document = app.documents.add(
DocumentColorSpace.RGB,
width = 720*mm,
height = 720*mm,
);
document = app.activeDocument;
var firstImageLayer = true;
var newLayer;
var thisPlacedItem;
var posX=10;
var posY=30;
var count=0;
// create document list from files in selected folder
var imageList = selectedFolder.getFiles();
for (var i = 0; i < imageList.length; i++) {
if (imageList[i] instanceof File) {
var fileName = imageList[i].name.toLowerCase();
if( (fileName.indexOf(".svg") == -1) ) {
continue;
} else {
if( firstImageLayer ) {
newLayer = document.layers[0];
firstImageLayer = false;
} else {
newLayer = document.layers.add();
}
// Give the layer the name of the image file
newLayer.name = fileName.substring(0, fileName.indexOf(".") );
// Place the image on the artboard
newGroup = newLayer.groupItems.createFromFile( imageList[i] );
newGroup.position = [ posX , posY ];
}
}
posX += newGroup.width;
if(posX > (newGroup.width*16)) {
posX = 0;
posY -= newGroup.height;
}
}
if( firstImageLayer ) {
// alert("The action has been cancelled.");
// display error message if no supported documents were found in the designated folder
alert("Sorry, but the designated folder does not contain any recognized image formats.\n\nPlease choose another folder.");
document.close();
importFolderAsLayers(getFolder());
}
} else {
// alert("The action has been cancelled.");
// display error message if no supported documents were found in the designated folder
alert("Rerun the script and choose a folder with images.");
//importFolderAsLayers(getFolder());
}
}
// Start the script off
importFolderAsLayers( getFolder() );
Simply remove these lines from your script:
document = app.documents.add(
DocumentColorSpace.RGB,
width = 720*mm,
height = 720*mm,
);

Snap.svg Load svg in order not available

I'm trying to get the (load in order) example to work. Here is my code.
I load snap.js and then my code in loadsvg.js it has my plugin. Then main.js with my code calling the function. I get a error in console that says "base.loadFilesDisplayOrdered is not a function". So it can't find it any help will be appreciated. Thanks
Snap.plugin( function( Snap, Element, Paper, global ) {
function addLoadedFrags( whichSVG, fragList, runWhenFinishedFunc ) { // This is called once all the loaded frags are complete
for( var count = 0; count < fragList.length; count++ ) {
myEl = whichSVG.append( fragList[ count ] );
}
runWhenFinishedFunc();
}
Paper.prototype.loadFilesDisplayOrdered = function( list, afterAllLoadedFunc, onEachElementLoadFunc ) {
var image, fragLoadedCount = 0, listLength = list.length, fragList = new Array(), whichSVG = this;
for( var count = 0; count < listLength; count++ ) {
(function() {
var whichEl = count,
fileName = list[ whichEl ],
image = Snap.load( fileName, function ( loadedFragment ) {
fragLoadedCount++;
onEachElementLoadFunc( loadedFragment, fileName );
fragList[ whichEl ] = loadedFragment;
if( fragLoadedCount >= listLength ) {
addLoadedFrags( whichSVG, fragList, afterAllLoadedFunc );
}
} );
})();
}
};
});
Then i call it in main.js
var base = Snap("#svgout");
console.log(base);
var myLoadList = [ "svgs/layer.svg", "svgs/cutout.svg" ];
var myDisplayList = { "Bird.svg": "zoom", "Dreaming_tux.svg": "fade" };
base.loadFilesDisplayOrdered( myLoadList, onAllLoaded, onEachLoaded );
The problem is, you are trying to create Snap into a div element. Snap only works on SVG elements.
Change,
<div id="svgout"></div>
to
<svg id="svgout"></svg>
And the error should go away.
jsfiddle

Add an ID to a canvas using JavaScript

I'm trying to add an ID to a canvas using JavaScript however I'm trying to modify the following specific code. Please note, I am only assuming that this is where I would set the attribute. Cheers for any help.
THREE.CanvasRenderer = function ( parameters ) {
console.log( 'THREE.CanvasRenderer', THREE.REVISION );
parameters = parameters || {};
var _this = this,
_renderData, _elements, _lights,
_projector = new THREE.Projector(),
_canvas = parameters.canvas !== undefined
? parameters.canvas
: document.createElement( 'canvas' ),
_canvasWidth = _canvas.width,
_canvasHeight = _canvas.height,
_canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
_canvasHeightHalf = Math.floor( _canvasHeight / 2 ),
_viewportX = 0,
_viewportY = 0,
_viewportWidth = _canvasWidth,
_viewportHeight = _canvasHeight,
_pixelRatio = 1,
_context = _canvas.getContext( '2d', {
alpha: parameters.alpha === true
} ),
You can just set the id property directly:
_canvas.id = 'whatever';
Edit
The above code should work, but it will need to be after the large variable initialization block you have:
// start var initialization
var _this = this,
_renderData, _elements, _lights,
_projector = new THREE.Projector(),
_canvas = parameters.canvas !== undefined
? parameters.canvas
: document.createElement( 'canvas' ),
_canvasWidth = _canvas.width,
_canvasHeight = _canvas.height,
_canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
_canvasHeightHalf = Math.floor( _canvasHeight / 2 ),
_viewportX = 0,
_viewportY = 0,
_viewportWidth = _canvasWidth,
_viewportHeight = _canvasHeight,
_pixelRatio = 1,
_context = _canvas.getContext( '2d', {
alpha: parameters.alpha === true
} ),
... more code,
theEnd = true;
// end var initialization
_canvas.id = 'whatever';
^ this whole thing is one big var initialization. At some point there it will end and there will probably be a semicolon. That's where you will add the id code.
I think you were getting an unexpected token error because you were trying to add some code between the commas in the var initialization.

Indesign script update window?

Edit: I am also open to other suggestions on what I could do.
How can I update my window with the onChange event? My solution works, but I need the groups to collapse when not visible.
w.DD.onChange = function() {
switch (this.selection.text){
case 'Headline':
if(w.visiblegroup)
w.visiblegroup.visible = false;
w.visiblegroup = w.texted;
w.texted.visible = true;
break;
}
}
I have tried to use w.show, w.update(with documentation, still not sure what .update actually does) after adding the elements in the case itself. But I can't figure this out.
w.DD.onChange = function() {
switch (this.selection.text){
case 'Headline':
w.add('checkbox', undefined, 'User-Color');
//w.show();
w.update();
break;
}
}
Does anyone have a clue how this might work?
I generally avoid using LayoutManager and do all teh maths by myself which I trust better but that's my humble opinion…
var w = new Window("dialog");
w.preferredSize = [200,200];
w.DD = w.add( 'dropdownlist', undefined, ["A","B"] );
w.DD.selection = 0;
w.DD.alignment = ["fill","top"];
//Setting a stacked group to items overlay
w.gp = w.add('group');
w.gp.orientation = 'stack';
w.gp.alignment = ["fill","top"];
w.gp.alignChildren = ["fill","top"];
w.gp.p1 = w.gp.add('panel',undefined, "A");
w.gp.p2 = w.gp.add('panel',undefined, "B");
//dummy text to show "collapsing"
w.st = w.add('statictext',undefined, "Collapse ?");
w.DD.onChange = function() {
w.gp.p1.visible = w.DD.selection==0;
w.gp.p2.visible = !w.gp.p1.visible;
w.gp.p2.size.height =100;
w.gp.size.height = w.gp.p1.visible? 50 : 100;
w.st.location.y = w.gp.location.y+w.gp.size.height+10;
}
w.onShow = function() {
w.gp.p2.visible=false;
w.gp.size.height = w.gp.p1.size.height = 50;
w.st.location.y = w.gp.location.y+w.gp.size.height+10;
}
w.show();
Loic
To collapse the groups and window you will need to use the layout() method of your window. This will load the LayoutManager that controls the automatic layout behavior for a window or container. The LayoutManager has a method called layout() too, this method invokes the automatic layout behaviour and invoked automatically the first time the window is displayed. Thereafter, the script must invoke it explicitly like so:
window.layout().layout();
An example of how to use the layout manager by Gerald Singelmann:
function main() {
var win = new Window("dialog");
var maingroup = win.add("panel");
maingroup.orientation = "column";
add_group( maingroup );
var show_btn = win.add("button", undefined, "show");
show_btn.onClick = function() {
var txt = "";
for (var n = 0; n < maingroup.children.length; n++) {
txt += maingroup.children[n].edit.text + "\n";
}
alert("Da steht: \n" + txt );
}
win.show();
function add_group( maingroup ) {
var group = maingroup.add( "group" );
group.edit = group.add("edittext", [undefined, undefined, 200, 20], maingroup.children.length );
group.plus = group.add("button", undefined, "+");
group.plus.onClick = add_btn;
group.minus = group.add("button", undefined, "-");
group.minus.onClick = minus_btn;
group.index = maingroup.children.length - 1;
win.layout.layout( true );
return group;
}
function add_btn ( e ) {
add_group( maingroup );
}
function minus_btn ( e ) {
var ix = this.parent.index;
maingroup.remove( maingroup.children[ix] );
win.layout.layout( true );
}
}
source

Categories

Resources