How I can save file with script Photoshop? - javascript

I want to write a script that would substitute different text from a text file into my shalon and save the image in jpeg format.
An error occurs: "This function may not be available in this version of Photoshop" on this line:
activeDocument.saveAs(saveFile, jpgSaveOptions, true,Extension.LOWERCASE);
My code:
while(!myFile.eof)
{
line = myFile.readln();
createText(line);
var thistimestamp = Math.round(new Date().getTime() / 1000);
saveFile = new File( "/c/Users/marki/Desktop/Temp001/" +thistimestamp)
saveOptions = new JPEGSaveOptions();
saveOptions.embedColorProfile = true;
saveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
saveOptions.matte = MatteType.NONE;
saveOptions.quality = 9;
app.activeDocument.saveAs(saveFile, saveOptions, true,Extension.LOWERCASE);
}
I use Adobe Photoshop: 2017.0.0 20161012.r.53 2016/10/12:23:00:00 CL 1094006 ( x64)

You missed off the extension :D
saveFile = new File( "c:\\temp\\" + thistimestamp) + ".jpg");

Taking that your script createFile() is well defined and working, you are missing document creation command app.documents.add() before you start issuing commands. You are also missing file open procedures. When added, the code works fine:
function createText(fface, size, colR, colG, colB, content, tX, tY) {
var artLayerRef = app.activeDocument.artLayers.add()
artLayerRef.kind = LayerKind.TEXT
textColor = new SolidColor();
textColor.rgb.red = colR;
textColor.rgb.green = colG;
textColor.rgb.blue = colB;
textItemRef = artLayerRef.textItem
textItemRef.font = fface;
textItemRef.contents = content;
textItemRef.color = textColor;
textItemRef.size = size
textItemRef.position = new Array(tX, tY)
}
var myFile = new File("/c/temp/myfile.txt");
myFile.open('r');
while(!myFile.eof) {
app.documents.add();
line = myFile.readln();
createText(line,10,2,2,2,line,10,10);
var thistimestamp = Math.round(new Date().getTime() / 1000);
saveFile = new File( "/c/temp/" +thistimestamp)
saveOptions = new JPEGSaveOptions();
saveOptions.embedColorProfile = true;
saveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
saveOptions.matte = MatteType.NONE;
saveOptions.quality = 9;
app.activeDocument.saveAs(saveFile, saveOptions, true, Extension.LOWERCASE);
}
This code is tested with version 20.0.2 20181219.r.30 2018/12/19: 1202136 x64
The text file content is:
And the result in Photoshop is:
Of course, all three documents are saved as jpegs in c:\temp.
In case you don't have a working createText function, you can find an example in this article. The function in this example is taken from that article.

Related

[indesign][js] dialog or palette - not show up

have problem with script.
need open a window with some information, which will automatically disappear after 3 seconds.
my code:
#targetengine "session"
var windowX = new Window("dialog"); // v2 palette
windowX.orientation = "row";
windowX.preferredSize.width = 200;
windowX.preferredSize.height = 200;
windowX.alignChildren = ["center","center"];
windowX.spacing = 15;
windowX.margins = 16;
var image1_imgString = "%C2%89PNG%0D%0A%1A..."
var image1 = windowX.add("image", undefined, File.decode(image1_imgString), {name: "image1"});
windowX.show();
dialog show, palette not
if I add ...
var timerBreak = new Date().getTime() + 3000;
var now = new Date().getTime();
while(now<timerBreak){
now = new Date().getTime()
}
windowX.close();
nothing happend (happend: first: loop, next: window show and close at the same time) - why?
if i add ...
windowX.addEventListener('show',function(){
...
}
same ...
but if i add alert("dhgkjsd") ... for check ... dialog (or palette) show and wait for click on messagaebox
how to make a timer that will close the displayed window 3 seconds after opening?
Unfortunately, I do not have a copy of InDesign to test this, but the code below works in AfterEffects.
#targetengine "session"
// To be called later
function closeMe() {
windowX.close();
}
// Timer as a variable
var delay = 3000;
// a pallette, and not a modal, like in your
// original code, because the modal is UI blocking
var windowX = new Window("palette");
windowX.orientation = "row";
windowX.preferredSize.width = 200;
windowX.preferredSize.height = 200;
windowX.alignChildren = ["center","center"];
windowX.spacing = 15;
windowX.margins = 16;
windowX.show();
// This is the key part
app.setTimeout(closeMe,delay);
app.setTimeout() has been suggested as a way of delaying code execution, which is what you need in this case (delaying of windowX.close()). Please note the author's comments (check the link) - app.setTimeout() has been made available from AE version CC 2015.
It can be done this way:
var windowX = new Window("palette");
windowX.orientation = "row";
windowX.preferredSize.width = 200;
windowX.preferredSize.height = 200;
windowX.alignChildren = ["center","center"];
windowX.spacing = 15;
windowX.margins = 16;
// var image1_imgString = "%C2%89PNG%0D%0A%1A..."
// var image1 = windowX.add("image", undefined, File.decode(image1_imgString), {name: "image1"});
windowX.show();
// here is the magic
windowX.update();
$.sleep(3000); // 3 seconds
windowX.hide();
windowX = null;
Based on the example from here: https://community.adobe.com/t5/illustrator-discussions/auto-close-alert-message/td-p/9398258
#Yuri ... windowX don't show before $.sleep (use instead var timerBreak...) - but only my Mac. Another Mac - your code works.
I write something like this:
//create windowX
var oneIdleTask = app.idleTasks.add({
name: "one_idle_task",
sleep: 1
}); // sleep not working here - write 3000 and nothing change
var onIdleEventListener = oneIdleTask.addEventListener(IdleEvent.ON_IDLE,
function() {
var oneIdleTaskName = "one_idle_task";
var oneIdleTask = app.idleTasks.itemByName(oneIdleTaskName);
if (oneIdleTask != null) {
oneIdleTask.remove();
$.sleep(3000) //<- write sleep here ... but deley is ok (for me) without this
windowX.hide();
}
}
);
windowX.show();

Add line numbering to a .docx with ActiveXObject('Word.Application')

Hi i want to add line numbering to the opened .docx file before converting it to .pdf and i really didn't find how to do that on code, it is converting my .docx file to pdf but i wanna add line numbering too, am using ActiveXObject with javascript to do that on server
var obj = new ActiveXObject("Scripting.FileSystemObject");
var docPath = WScript.Arguments(0);
docPath = obj.GetAbsolutePathName(docPath);
var pdfPath = docPath.replace(/\.doc[^.]*$/, ".pdf");
var objWord = null;
try
{
objWord = new ActiveXObject("Word.Application");
objWord.Visible = false;
var objDoc = objWord.Documents.Open(docPath);
var format = 17;
objDoc.SaveAs(pdfPath, format);
objDoc.Close();
WScript.Echo("Saving '" + docPath + "' as '" + pdfPath + "'...");
}
catch(e){
WScript.Echo(e);
}
finally
{
if (objWord != null)
{
objWord.Quit();
}
}
If you want to automate Word but you don't know how to do it in code, start recording a macro, do what you want, then stop recording and review the code. You should be able to figure out what you need from the generated code.
Here's an example of a recorded macro:
Sub Macro1
With Selection.PageSetup
With .LineNumbering
.Active = True
.StartingNumber = 1
.CountBy = 1
.RestartMode = wdRestartContinuous
.DistanceFromText = wdAutoPosition
End With
.Orientation = wdOrientPortrait
.TopMargin = InchesToPoints(1)
.BottomMargin = InchesToPoints(1)
.LeftMargin = InchesToPoints(1)
.RightMargin = InchesToPoints(1)
.Gutter = InchesToPoints(0)
.HeaderDistance = InchesToPoints(0.5)
.FooterDistance = InchesToPoints(0.5)
.PageWidth = InchesToPoints(8.5)
.PageHeight = InchesToPoints(11)
.FirstPageTray = wdPrinterDefaultBin
.OtherPagesTray = wdPrinterDefaultBin
.SectionStart = wdSectionNewPage
.OddAndEvenPagesHeaderFooter = False
.DifferentFirstPageHeaderFooter = False
.VerticalAlignment = wdAlignVerticalTop
.SuppressEndnotes = False
.MirrorMargins = False
.TwoPagesOnOne = False
.BookFoldPrinting = False
.BookFoldRevPrinting = False
.BookFoldPrintingSheets = 1
.GutterPos = wdGutterPosLeft
End With
End Sub
Based on that example, I would assume your code would need to include this for line numbers:
objDoc.PageSetup.LineNumbering.Active = true;

export separate art boards as PNG illustrator script

I've created to a simple illustrator script to loop through the artboards and export each as a PNG back into the folder that the original illustrator file is in. At least I thought I had. I don't need to do anything complicated with layers or different formats this is just a speed up production sort of a thing. I'm a bit rusty on .jsx and appreciate there are similar solutions out there, but I can't get this to run. It seems to fail on the doc.ExportFile line but I really can't see what I'm doing wrong. I'd appreciate anyone taking a look:
var doc = activeDocument;;//Gets the active document
var numArtboards = doc.artboards.length;//returns the number of artboards in the document
var basePath = new File($.fileName).parent.fsName;
$.writeln(doc)
var options;
options = new ExportOptionsPNG24();
options.artBoardClipping = true;
options.matte = false;
options.horizontalScale = 100;
options.verticalScale = 100;
options.transparency = true;
for (var i = 0; i < numArtboards; i++ ) {
doc.artboards.setActiveArtboardIndex( i );
var artboardName = doc.artboards[i].name;
var destFile = new File('/' + artboardName + ".png");
doc.exportFile(destFile, ExportFormat.PNG24 , options);
}
The main problem seemed to be that you hve to have a destination path with the file name. This now seems to work: (You may need to altter the fileNamr generation as code just gets the first nune letters of a filename)
var doc = app.activeDocument;;//Gets the active document
var fleName = doc.name.slice(0, 9)//Get the file code number not the full name;
var numArtboards = doc.artboards.length;//returns the number of artboards in the document
var filePath = (app.activeDocument.fullName.parent.fsName).toString().replace(/\\/g, '/');
$.writeln("fleName= ",fleName)
$.writeln("numArtboards= ",numArtboards)
$.writeln("filePath= ",filePath);
var options = new ExportOptionsPNG24();
for (var i = 0; i < numArtboards; i++ ) {
doc.artboards.setActiveArtboardIndex( i );
options.artBoardClipping = true;
options.matte = false;
options.horizontalScale = 100;
options.verticalScale = 100;
options.transparency = true;
var artboardName = doc.artboards[i].name;
$.writeln("artboardName= ", artboardName);
var destFile = new File(filePath + "/" + fleName + " " + artboardName + ".png");
$.writeln("destFile= ",destFile);
doc.exportFile(destFile,ExportType.PNG24,options);
}

Mathquill how to write formula into pdf file

I'm trying to create a webpage where users are able to write formulas (rendered by mathquill).
This is the code:
createButton(document.body,
function()
{
var para1 = parent.frame1.document.createElement("p");
para1.setAttribute("id","Line"+i.toString());
var t1 = parent.frame1.document.createTextNode("Line "+i.toString()+":");
para1.appendChild(t1);
parent.frame1.document.body.appendChild(para1);
var para = parent.frame1.document.createElement("p");
para.setAttribute("id","math"+i.toString());
para.setAttribute("class", "mq-math-mode");
var t = parent.frame1.document.createTextNode("");
para.appendChild(t);
parent.frame1.document.body.appendChild(para);
latex = $('#basic-latex').on('keydown keypress', function() {
var prev = latex.val();
setTimeout(function() {
var now = latex.val();
if (now !== prev) mq.latex(now);
});
});
mq = MQ.MathField(para, {
autoSubscriptNumerals: true,
handlers: { edit: function() {
if (!latex.is(':focus')) latex.val(mq.latex());
} }
});
//latex.val(mq.latex());
//mathField = MQ.MathField(para, {spaceBehavesLikeTab: true});
i = i+1;
}
, "Create new line");
Then, I would like to save formulas in a pdf file.
I'm using the package jsPDF, but I'm not able to write the rendered formulas in the pdf. Is anybody able to help me?
Thanks a lot in advance
I add the code to create the PDF.
var doc = new jsPDF();
var str = mq.latex();
var src = 'http://latex.codecogs.com/png.latex?'+str
var som = new Image();
som.src = src;
var imgData = 'data:image/png;base64,'+ Base64.encode(som);
doc.addImage(imgData, 'png', 10, 50);
doc.save('Test.pdf');

Photoshop Javascript for resize based on filesize

I have a folder with a lot of subfolders, each with a bunch of TIFs and PSD files inside. Some of these have transparency in them while some don't. These files vary massively in size.
I need all the files to be turned into JPGs, or if they contain transparency, PNGs. I require the files to be 200kb or less and don't really mind how large they are as long as they aren't scaled up.
Someone on a forum (who I'm insanely thankful for) wrote a fair bit of code for it, which my friend modified to suit exactly what I was asking and we're nearly there now.
It worked fine, the only problem being that a lot of images came out 1x1 pixel and a solid block of colour.
We've found this was consistently happening with the same images for some reason, but couldn't work out what exactly it was in these images.
Now Mr forum blokey ( http://www.photoshopgurus.com/forum/members/paul-mr.html ) modified the script and it now seems to work fine with PSDs.
It's working with TIFs with transparency but some of the TIFs with 100% opacity it just won't work on. I can't find much that's consistent with these files other than the colour blue, though this just could be a massive coincidence and probably is (there's a lot of blue in the images I've been dealing with).
Below is a link to the thread in which the code was first written. Paul MR seems to think the colorsampler bit is a little suspect so perhaps that's what's causing the problems (blueness?).
http://www.photoshopgurus.com/forum/photoshop-actions-automation/34745-batching-tiffs-jpg-png-w-automatic-resize-based-filesize.html
I wish I could do a little more to try and work this out myself but I've barely a speck of understanding on this stuff, I just know when there's a situation where a bit of scripting could help out.
Below is the script as it currently stands:
#target PhotoshopString.prototype.endsWith = function(str) {
return (this.match(str + "$") == str)
} String.prototype.startsWith = function(str) {
return this.indexOf(str) == 0;
};
var desiredFileSize = 200000;
app.bringToFront();
app.displayDialogs = DialogModes.NO;
main();
//app.displayDialogs = DialogModes.YES;
function main() {
var topLevelFolder = Folder.selectDialog("Please select top level folder.");
if (topLevelFolder == null)return;
var FileList = [];
getFileList(topLevelFolder);
var startRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
for (var f in FileList) {
app.open(FileList[f]);
activeDocument.changeMode(ChangeMode.RGB);
try {
activeDocument.mergeVisibleLayers();
} catch(e) {} var Name = decodeURI(app.activeDocument.name).replace(/.[^.] + $ /, '');
if (hasTransparency(FileList[f])) {
var saveFile = File(FileList[f].path + "/" + Name + ".png");
SavePNG(saveFile);
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
} else {
var saveFile = File(FileList[f].path + "/" + Name + ".jpg");
SaveForWeb(saveFile, 80);
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
} app.preferences.rulerUnits = startRulerUnits;
} function getFileList(folder) {
var fileList = folder.getFiles();
for (var i = 0; i < fileList.length; i++) {
var file = fileList[i];
if (file instanceof Folder) {
getFileList(file);
} else {
if ((file.name.endsWith("tiff") || file.name.endsWith("tif") || file.name.endsWith("psd")) && ! file.name.startsWith("._"))FileList.push(file);
}
}
} alert(FileList.length + " files have been modified.");
} function hasTransparency(file) {
if (file.name.endsWith("tiff") || file.name.endsWith("tif")) {
var sample = app.activeDocument.colorSamplers.add([new UnitValue(1.5, 'px'), new UnitValue(1.5, 'px')]);
try {
sample.color.rgb.hexValue;
sample.remove();
return false;
} catch(e) {
sample.remove();
return true;
}
} var doc = activeDocument;
if (doc.activeLayer.isBackgroundLayer)return false;
var desc = new ActionDescriptor();
var ref = new ActionReference();
ref.putProperty(charIDToTypeID("Chnl"), charIDToTypeID("fsel"));
desc.putReference(charIDToTypeID("null"), ref);
var ref1 = new ActionReference();
ref1.putEnumerated(charIDToTypeID("Chnl"), charIDToTypeID("Chnl"), charIDToTypeID("Trsp"));
desc.putReference(charIDToTypeID("T "), ref1);
executeAction(charIDToTypeID("setd"), desc, DialogModes.NO);
var w = doc.width.as('px');
var h = doc.height.as('px');
var transChannel = doc.channels.add();
doc.selection.store(transChannel);
if (transChannel.histogram[255] != (h * w)) {
transChannel.remove();
return true;
} else {
transChannel.remove();
return false;
}
};
function SavePNG(saveFile) {
pngSaveOptions = new PNGSaveOptions();
activeDocument.saveAs(saveFile, pngSaveOptions, true, Extension.LOWERCASE);
var actualFilesize = saveFile.length;
var ratio = desiredFileSize / actualFilesize;
if (ratio < 1) {
var imageScale = Math.sqrt(ratio);
activeDocument.resizeImage(activeDocument.width * imageScale, activeDocument.height * imageScale, activeDocument.resolution, ResampleMethod.BICUBICSMOOTHER);
activeDocument.saveAs(saveFile, pngSaveOptions, true, Extension.LOWERCASE);
}
}
function SaveForWeb(saveFile, jpegQuality) {
var sfwOptions = new ExportOptionsSaveForWeb();
sfwOptions.format = SaveDocumentType.JPEG;
sfwOptions.includeProfile = false;
sfwOptions.interlaced = 0;
sfwOptions.optimized = true;
sfwOptions.quality = jpegQuality;
activeDocument.exportDocument(saveFile, ExportType.SAVEFORWEB, sfwOptions);
var actualFilesize = saveFile.length;
var ratio = desiredFileSize / actualFilesize;
if (ratio < 1) {
var imageScale = Math.sqrt(ratio);
activeDocument.resizeImage(activeDocument.width * imageScale, activeDocument.height * imageScale, activeDocument.resolution, ResampleMethod.BICUBICSMOOTHER);
activeDocument.exportDocument(saveFile, ExportType.SAVEFORWEB, sfwOptions);
}
}

Categories