Split window java script for InDesign - adobe-indesign

Does anyone know of or can help me figure out how to create a script for InDesign to do the Split Screen command, this is found under menu selection Window > Arrange > Split Window. Thank you!

Basically this should work:
app.menuActions.item("$ID/Split Window").invoke()
But actually it sometimes works and sometimes doesn't. I can't tell why.
It works more or less stable as a toggle split/unsplit this way:
try {
app.menuActions.item("$ID/Split Window").invoke()
} catch(e) {
app.menuActions.item("$ID/Unsplit Window").invoke()
}
Probably there is some property, which you can read and run split command only if the window is not splitted already. I don't know.
Update
The list of 'menuActions' you can get with this script:
var list = "ID\tName\tArea\n";
var i = 0;
for (var i=0; i<app.menuActions.length; i++) {
var m = app.menuActions[i];
list += m.id + "\t" + m.name + "\t" + m.area + "\n";
}
f = File("menu_actions.txt");
f.encoding = "UTF-8";
f.open("w");
f.write(list);
f.close();
f.execute(); // to open the txt file immediately
\\ alert(i + " actions wese saved to " + f.fsName);
All credits to Kasyan Servetsky: http://kasyan.ho.ua/tips/indesign_script/all/open_menu_item.html

Related

how can I extract text from indd files or indesign files using python programs?

I need to create an api where user will provide indesign file and I need to extract text from it.
Basically it can be done this way:
from win32com.client import Dispatch
app = Dispatch('InDesign.Application.CS6')
doc = app.Open(r"d:\text.indd")
contents = ""
for story in doc.stories: contents += story.contents + "\n"
f = open(r"d:\text.txt", "w", encoding="utf8")
f.write(contents)
f.close()
doc.Close()
But perhaps there can be glitches with special symbols. I believe it makes sense to use the native Javascript Extendscript for this task. Something like this:
var doc = app.open(File("d:/text.indd"));
var stories = doc.stories.everyItem().getElements();
var contents = "";
for (var i=0; i<stories.length; i++) contents += stories[i].contents + "\n";
var file = File("d:/text.txt");
file.open("w");
file.write(contents);
file.close();
doc.close();

Adding multiple CC recipients in VBScript; Recipient.Type not working

I am working on a jsx (extendscript project) in which I am calling a VBS snippet with app.doScript. I cannot get the email_cc and email_cc2 recipients to show up as cc; they are stuck in the main "To" sending. I will not know in advance whether they exist in the users' address book, so I am adding them as recipients than trying to set their Type.
var vbs = 'Dim objOutl\r';
vbs += 'Set objOutl = CreateObject("Outlook.Application")\r';
vbs += 'Set objMailItem = objOutl.CreateItem(olMailItem)\r';
vbs += 'objMailItem.Display\r';
vbs += 'strEmailAddress = "' + email_address + '"\r';
vbs += 'objMailItem.Recipients.Add strEmailAddress\r';
vbs += 'strSubject = "' + the_subject + '"\r';
vbs += 'objMailItem.Subject = strSubject\r';
vbs += 'objMailItem.Body = "' + the_bodytext + '"\r';
if (email_cc && email_cc != "") {
vbs += 'Set cc1Recipient = objMailItem.Recipients.Add ("' + email_cc + '")\r';
if (email_cc2 && email_cc2 != "") {
vbs += 'Set cc2Recipient = objMailItem.Recipients.Add ("' + email_cc2 + '")\r';
vbs += 'cc1Recipient.Type = olCC\r';
vbs += 'cc2Recipient.Type = olCC\r';
}
else {
vbs += 'cc1Recipient.Type = olCC\r';
}
}
if (has_attachment) {
vbs += 'objMailItem.Attachments.Add "' + pdf_file + '"\r';
}
Check out the following points:
Try to use the fully qualified name in the code with the enum name, for example:
OlMailRecipientType.olCC
Use the Resolve method which attempts to resolve a recipient object against the address book. It returns true if the recipient was resolved.
Call the Save method to apply changes made through the OOM. Sometimes it makes sense to close the item, switch to another Outlook item, and then come back to check out results. Outlook caches changes and doesn't propagate changes made using the OOM immediately.
Read more about these methods and properties in the How To: Fill TO,CC and BCC fields in Outlook programmatically article.

ExtendScript Toolkit CCC - Adding a leading zero if only a single digit is found

I have a script that changes the layer name of my illustrator file to "Test 1, Test 2, etc..." All I want to accomplish is to add leading zero to single digits. "Test 01, Test 02 ... Test 10, Test 11, etc..."
var doc = app.activeDocument;
idLayers("Test "); // Rename visible layers
// Hidden layers will be skipped and not counted
function idLayers(prefix){
var counter = 1;
for(i=0;doc.layers.length>i;i++){
var currentLayer = doc.layers[i];
// if layer is visible...
if (currentLayer.visible) {
currentLayer.name= prefix + counter;
counter++;
}
}
}
I found the following that would help but I'm not sure where to add it to the above code.
function pad(n) {
return (n < 10) ? ("0" + n) : n;
}
Total noob here so any help would be greatly appreciated. Thank you in advance!
You simply need to add the function that you already found at the end of your script (or at the beginning, it does not really matter) and then call it in the line, where the layer is named. So the whole script would look like this:
var doc = app.activeDocument;
idLayers("Test "); // Rename visible layers
// Hidden layers will be skipped and not counted
function idLayers(prefix){
var counter = 1;
for(i=0;doc.layers.length>i;i++){
var currentLayer = doc.layers[i];
// if layer is visible...
if (currentLayer.visible) {
currentLayer.name= prefix + pad(counter);
counter++;
}
}
}
function pad(n) {
return (n < 10) ? ("0" + n) : n;
}

Script Works on Win 7, Not on Server 2003

I have a script that is rather simple, it boots up WinSCP and checks the directory for a file that starts with "TSA". If the file exists, it exits, if it does not exist, it transfers over a new file.
Its up and running on my Windows 7 machine, that is where i created it - but when i transfer it over to my server [windows server 2003] it never finds the file.
My script:
var FILEPATH = "../zfinance/TSA";
// Session to connect to
var SESSION = "someplace#somewhere.com";
// Path to winscp.com
var WINSCP = "c:\\program files\\winscp\\winscp.com";
var filesys = WScript.CreateObject("Scripting.FileSystemObject");
var shell = WScript.CreateObject("WScript.Shell");
var logfilepath = filesys.GetSpecialFolder(2) + "\\" + filesys.GetTempName() + ".xml";
var p = FILEPATH.lastIndexOf('/');
var path = FILEPATH.substring(0, p);
var filename = FILEPATH.substring(p + 1);
var exec;
// run winscp to check for file existence
exec = shell.Exec("\"" + WINSCP + "\" /log=\"" + logfilepath + "\"");
exec.StdIn.Write(
"option batch abort\n" +
"open \"" + SESSION + "\"\n" +
"ls \"" + path + "\"\n" +
"exit\n");
// wait until the script finishes
while (exec.Status == 0)
{
WScript.Sleep(100);
WScript.Echo(exec.StdOut.ReadAll());
}
if (exec.ExitCode != 0)
{
WScript.Echo("Error checking for file existence");
WScript.Quit(1);
}
// look for log file
var logfile = filesys.GetFile(logfilepath);
if (logfile == null)
{
WScript.Echo("Cannot find log file");
WScript.Quit(1);
}
// parse XML log file
var doc = new ActiveXObject("MSXML2.DOMDocument");
doc.async = false;
doc.load(logfilepath);
doc.setProperty("SelectionNamespaces",
"xmlns:w='http://winscp.net/schema/session/1.0'");
doc.setProperty("SelectionLanguage", "XPath");
var nodes = doc.selectNodes("//w:file/w:filename[starts-with(#value, '" + filename + "')]");
if (nodes.length > 0)
{
WScript.Echo("File found");
WScript.Quit(0);
}
else
{
WScript.Echo("File not found");
WScript.Quit(1);
}
After much investigation, i think i've found the piece of code that does not function properly:
// parse XML log file
var doc = new ActiveXObject("MSXML2.DOMDocument.6.0");
doc.async = false;
doc.load(logfilepath);
doc.setProperty("SelectionNamespaces",
"xmlns:w='http://winscp.net/schema/session/1.0'");
The only problem is, i have no idea why. The log file at this point should be written over with the xml code, but this does not happen.
Thanks in advance for any help.
And the answer is........... WinSCP on Windows Server 2003 was WAY out of date. So out of date that the log was completely different from one version to the next. Updated and VIOLA! Problem solved. Thanks for your help.
Maybe you need to install MSXML2.DOMDocument.6.0
http://msdn.microsoft.com/en-us/library/windows/desktop/cc507436%28v=vs.85%29.aspx
If you open up regedit and look for "MSXML2.DOMDocument.6.0" does it find it? If so maybe security settings for the script need to be set in order to be able to create an activeX object.
What can you see when you put some stuff in try catch?
try{
//stuff
}catch(e){
WScript.Echo(e.message);
}

Script to rename files

I have about 2200 different files in a few different folders, and I need to rename about about 1/3 of them which are in their own subfolder. Those 700 are also in various folders as well.
For example, there might be
The top-most folder is Employees, which has a few files in it, then the folder 2002 has a few, 2003 has more files, 2004 etc.
I just need to attach the word "Agreement" before the existing name of each file. So instead of it just being "Joe Schmoe.doc" It would be "Agreement Joe Schmoe.doc" instead.
I've tried googling such scripts, and I can find stuff similar to what I want but it all looks completely foreign to me so I can't understand how I'd modify it to suit my needs.
Oh, and this is for windows server '03.
I need about 2 minutes to write such script for *NIX systems (may be less), but for Windows it is a long song ... ))
I've write simple VBS script for WSH, try it (save to {script-name}.vbs, change Path value (on the first line of the script) and execute). I recommend to test script on small amount of data for the first time just to be sure if it works correctly.
Path = "C:\Users\rootDirectory"
Set FSO = CreateObject("Scripting.FileSystemObject")
Sub visitFolder(folderVar)
For Each fileToRename In folderVar.Files
fileToRename.Name = "Agreement " & fileToRename.Name
Next
For Each folderToVisit In folderVar.SubFolders
visitFolder(folderToVisit)
Next
End Sub
If FSO.FolderExists(Path) Then
visitFolder(FSO.getFolder(Path))
End If
I used to do bulk renaming with batch scripts under Windows. I know it's a snap on *nix (find . -maxdepth N -type f -name "$pattern" | sed -e 'p' -e "s/$str1/$str2/g" | xargs -n2 mv). Buf after some struggle in vain, I found out, to achieve that effect using batch scripts is almost impossible. So I turned to javascript.
With this script, you can add prefix to file names by 'rename.js "s/^/Agreement /" -r *.doc'. A caret(^) means to match the beginning. The '-r' options means 'recursively', i.e. including sub-folders. You can specify a max depth with the '-d N' option. If neither '-r' or '-d N' is given, the script does not recurse.
If you know the *nix 'find' utility, you would notice that 'find' will match the full path (not just the file name part) to specified regular expression. This behavior can be achieved by supplying the '-f' option. By default, this script will match the file name part with the given regular expression.
If you are familiar with regular expressions, complicated renaming is possible. For example, 'rename.js "s/(\d+)/[$1]/" *' which uses grouping to add brackets to number sequences in filenames.
// rename.js --- bulk file renaming utility (like *nix rename.pl)
// (c) Copyright 2012, Ji Han (hanji <at> outlook <dot> com)
// you are free to distribute it under the BSD license.
// oops... jscript doesn't have array.map
Array.prototype.map = function(f, t){
var o = Object(this);
var a = new Array(o.length >>> 0);
for (var i = 0; i < a.length; ++i){ if (i in o) a[i] = f.call(t, o[i], i, o) }
return a;
};
/// main
(function(){
if (WScript.Arguments.Length == 0){
WScript.Echo('rename "<operator>/<pattern>/<string>/[<modifiers>]" [-f] [-r] [-d <maxdepth>] [<files>]');
WScript.Quit(1);
}
var fso = new ActiveXObject('Scripting.FileSystemObject');
// folder is a Folder object [e.g. from fso.GetFolder()]
// fn is a function which operates on File/Folder object
var recurseFolder = function(folder, fn, depth, maxdepth){
if (folder.Files){
for (var e = new Enumerator(folder.Files); !e.atEnd(); e.moveNext()){
fn(e.item())
}
}
if (folder.Subfolders){
for (var e = new Enumerator(folder.SubFolders); !e.atEnd(); e.moveNext()){
fn(e.item());
if (depth < maxdepth){ arguments.callee(e.item(), fn, depth + 1, maxdepth) }
}
}
}
// expand wildcards (asterisk [*] and question mark [?]) recursively
// given path may be relative, and may contain environment variables.
// but wildcards only work for the filename part of a path.
// return an array of full paths of matched files.
// {{{
var expandWildcardsRecursively = function(n, md){
var pattern = fso.GetFileName(n);
// escape regex metacharacters (except \, /, * and ?)
// \ and / wouldn't appear in filename
// * and ? are treated as wildcards
pattern = pattern.replace(/([\[\](){}^$.+|-])/g, '\\$1');
pattern = pattern.replace(/\*/g, '.*'); // * matches zero or more characters
pattern = pattern.replace(/\?/g, '.'); // ? matches one character
pattern = pattern.replace(/^(.*)$/, '\^$1\$'); // matches the whole filename
var re = new RegExp(pattern, 'i'); // case insensitive
var folder = fso.GetFolder(fso.GetParentFolderName(fso.GetAbsolutePathName(n)));
var l = [];
recurseFolder(folder, function(i){ if (i.Name.match(re)) l.push(i.Path) }, 0, md);
return l;
}
// }}}
// parse "<operator>/<pattern>/<string>/[<modifiers>]"
// return an array splitted at unescaped forward slashes
// {{{
var parseExpr = function(s){
// javascript regex doesn't have lookbehind...
// reverse the string and lookahead to parse unescaped forward slashes.
var z = s.split('').reverse().join('');
// match unescaped forward slashes and get their positions.
var re = /\/(\\\\)*(?!\\)/g;
var l = [];
while (m = re.exec(z)){ l.push(m.index) }
// split s at unescaped forward slashes.
var b = [0].concat(l.map(function(x){ return s.length - x }).reverse());
var e = (l.map(function(x){ return s.length - x - 1 }).reverse()).concat([s.length]);
return b.map(function(_, i){ return s.substring(b[i], e[i]) });
}
// }}}
var expr = WScript.Arguments(0);
var args = [];
var options = {};
for (var i = 1; i < WScript.Arguments.Length; ++i){
if (WScript.Arguments(i).substring(0, 1) != '-'){
args.push(WScript.Arguments(i));
} else if (WScript.Arguments(i) == '-f'){
options['fullpath'] = true;
} else if (WScript.Arguments(i) == '-r'){
options['recursive'] = true;
} else if (WScript.Arguments(i) == '-d'){
options['maxdepth'] = WScript.Arguments(++i);
} else if (WScript.Arguments(i) == '--'){
continue;
} else {
WScript.Echo('invalid option \'' + WScript.Arguments(i) +'\'');
WScript.Quit(1);
}
}
if (options['maxdepth']){
var md = options['maxdepth'];
} else if (options['recursive']){
var md = 1<<31>>>0;
} else {
var md = 0;
}
var tokens = parseExpr(expr);
if (tokens.length != 4){
WScript.Echo('error parsing expression \'' + expr + '\'.');
WScript.Quit(1);
}
if (tokens[0] != 's'){
WScript.Echo('<operator> must be s.');
WScript.Quit(1);
}
var pattern = tokens[1];
var substr = tokens[2];
var modifiers = tokens[3];
var re = new RegExp(pattern, modifiers);
for (var i = 0; i < args.length; ++i){
var l = expandWildcardsRecursively(args[i], md);
for (var j = 0; j < l.length; ++j){
var original = l[j];
if (options['fullpath']){
var nouveau = original.replace(re, substr);
} else {
var nouveau = fso.GetParentFolderName(original) + '\\' + fso.GetFileName(original).replace(re, substr);
}
if (nouveau != original){
(fso.FileExists(original) && fso.GetFile(original) || fso.GetFolder(original)).Move(nouveau)
}
}
}
})();

Resources