renaming finder items IV

when we first started looking at batch renaming files, we saw how you could use automator to replace part of a filename with new text (see renaming finder items). here’s an applescript version of that functionality which makes batch renaming files in the finder even easier than automator.

this script works on batches of filenames that have something in common (eg. ‘12345 ThisFile_01’, ‘12345 ThisFile_02’, etc.) allowing the user to replace or add to that common element (eg. ‘ABCD_ThisFile_01’, ‘ABCD_ThisFile_02’, etc. … or … ‘12345 ThisFinishedFile_01’, ‘12345 ThisFinishedFile_02’, etc.)

the first part of the script references the selected finder items (the files to be changed) and the name of the first of these files. we use text item delimiters to strip the extension from that name :

tell application "Finder"
  set mgSelection to the selection
  set mgFirstName to name of item 1 of mgSelection
  set text item delimiters of AppleScript to "."
  set mgFirstName to text item 1 of mgFirstName
  set text item delimiters of AppleScript to ""
end tell

the next bit presents the user with two dialog windows. the first captures the change from text — with the filename from above as the initial default answer. the second captures the change to text — with the change from text as the initial default answer. including default answers in the dialog windows is a handy prompt for the user :

set mgChangeFromDialog to display dialog "What part of the filename do you want changed?" default answer mgFirstName with title "THIS SCRIPT CHANGES FILENAMES"
set mgChangeFrom to text returned of mgChangeFromDialog
delay 1
set mgChangeToDialog to display dialog "What is your new replacement text?" default answer mgChangeFrom with title "THIS SCRIPT CHANGES FILENAMES"
set mgChangeTO to text returned of mgChangeToDialog

here’s an example to make things clearer (hopefully). the first dialog is the change from window showing the first filename as it is presented to the user (left). on the right is that same window after the user specifies the part of the filename to change, before hitting ok :
screen grab of the change from dialog window

then the next dialog window — change to — pops up with that same user-defined text as the prompt (left). and the user specifies what that text should be changed to before hitting ok again (right) :
screen grab of the change to dialog window

you’ll notice in that script snippet above a one second delay between the presentation of the windows. this is purely a psychological gap to help the user realise that a new window has been presented. try it without the delay if you prefer.

next, just for shits and giggles, here’s a surly little message just in case the change from text is the same as the change to text. of course, this is entirely unnecessary — but good for a laugh :

considering case
  if mgChangeFrom = mgChangeTO then
    display dialog "OK — so you don't want any change at all." & return & return & "Thanks for wasting my time tosser." buttons {"get stuffed"} default button 1 giving up after 2
    error number -128
  end if
end considering

screen grab of surly message

that snippet demonstrates the handy ‘considering case’ control statement. this means the message would only get triggered if you tried to change “ThisFile” to “ThisFile” but not for “THISFILE” or “thisFILE” or “Thisfile” etc.

the rest of the script looks like this :

tell application "Finder"
  repeat with mgitem in mgSelection
    set mgOriginalName to name of mgitem
    set text item delimiters of AppleScript to mgChangeFrom
    set mgNameItems to text items of mgOriginalName
    set text item delimiters of AppleScript to ""
    set mgItemCount to count mgNameItems
    if mgItemCount is not 1 then
      set text item delimiters of AppleScript to mgChangeTO
      set mgNewName to mgNameItems as string
      set text item delimiters of AppleScript to ""
      set name of mgitem to mgNewName
    end if
  end repeat
end tell
set mgMessage to "All Done."
display dialog mgMessage

let’s use the examples from the dialog windows above to explain this part of the script. the files we are changing are pdfs. mgChangeFrom is ‘ThisFile’ and mgChangeTo is ‘ThisFinishedFile’. On the first pass through the loop, mgOriginalName will be the name of the first item in the Finder selection — ‘12345 ThisFile_01.pdf’. We set applescript’s text item delimiters (the characters which separate sections of text) to mgChangeFrom (‘ThisFile’) and then get the text items of mgOriginalName. this will give us the variable mgNameItems as a list — {“12345 “, “_01.pdf”}.

next we do a count of mgNameItems. if the list has only one item, it means mgOriginalName DOES NOT contain mgChangeFrom (eg. the filename ‘54321 ThatFile_31.pdf’ would return the list {“54321 ThatFile_31.pdf”}) and that file will be skipped over because the rest of the functionality is held within that if statement.

incidentally, if mgChangeFrom in our working example was ‘12345’ instead of ‘ThisFile’, the list returned would be {“”, ” ThisFile_01.pdf”} — that is, two list items — so it would pass the requirements of the if statement.

so, if the filename passes that if requirement we then change the text item delimiters to mgChangeTo (‘ThisFinishedFile’) and run the list items back together as a string — that is, {“12345 “, “_01.pdf”} becomes “12345 ThisFinishedFile_01.pdf”.

and finally there’s the line which actually does the name change. then the process is repeated for all the items in mgSelection. and we end with a message which alerts the user to the fact that the process is complete.

to turn this into a functioning app you’d add an on open handler and delete (or comment out) the line “set mgSelection to the selection”. the finished script would look like this :
screen grab of finished script

then you’d save it as an application, drag it to your sidebar, and drag-drop the files you want to rename onto it (left). and quicker than you can say “jiggle my janglers” the work’s done (right). you can see here how files that do not contain the change from text are simply skipped over :
screen grab of files being dropped onto app and finished result

so, this is the basic functioning script. but the next post will look at how to make it just a little more user friendly and robust. we need to add some error handling for different scenarios and maybe some other user safeguards.

’til then, keep grunting.


• related post : renaming finder items : renaming using automator or applescript.
• related post : renaming finder items II : renaming by list.
• related post : renaming finder items III : renaming by creation date.
• related post : renaming finder items IV — part 2 : the next step.

macgrunt icon

InDesign scripting : lesson 34

ok, here’s the last lesson (for now) on exporting each page of an InDesign file as a separate pdf using applescript. lesson 32 showed a basic solution and lesson 33 expanded it to allow for more naming options. this lesson will look at how to generate the pdf filenames from information saved in the InDesign file itself. this solution was prompted by comment 39 in this discussion :

I’m using InDesign to manage 200+ pages of tech sheets for a company … The obvious benefit of using InDesign and having all the tech sheets in a single file is because then I can edit and update Master Pages and have the changes reflected in all of the tech sheets. The major downside though is that when exporting the PDFs … the file name must be specified manually for each tech sheet.

as always, there are many ways to skin a cat. we’re going to look at two approaches — naming based on the heading text of each page, and naming based on script labels. both solutions rely on setting up the InDesign file in a particular way and both solutions begin with this basic setup (refer to the previous lessons for an explanation of these parts of the script) :

tell application id "com.adobe.InDesign"
  set raster resolution of interactive PDF export preferences to one hundred forty four ppi
  set (export reader spreads of interactive PDF export preferences) to false
  set mgFolder to file path of active document
  set mgDocName to name of active document
end tell

tell application "Finder"
  if (exists folder "the pdfs" of folder mgFolder) is false then
    make folder at mgFolder with properties {name:"the pdfs"}
  end if
end tell

tell application id "com.adobe.InDesign"
  repeat with x in pages of active document
    set mgPageName to name of x
    set page range of interactive PDF export preferences to mgPageName
    
    tell active document

      -- REST OF FUNCTIONALITY WILL GO IN HERE

      set mgFilePath to mgFolder & "the pdfs:" & mgText & ".pdf" as string
      export format interactive PDF to mgFilePath without showing options
    end tell
    
  end repeat
  display dialog "ALL DONE!" buttons {"OK"} default button 1
end tell

here’s a snippet of our InDesign file :
screen grab of tech sheets indesign file

there are a few different approaches you could use to pull out the heading on each page as the filename for each pdf. but the easiest way is to set up the InDesign file so that those heading text frames are on their own layer (for this example we’ve called the layer ‘header layer’). so, each page has only one text frame on the header layer — the heading. here’s the remainder of the code to be plugged into the basic script above :

set mgFrames to (text frames of x whose name of item layer is "header layer")
set mgFrame to item 1 of mgFrames
set mgText to contents of item 1 of mgFrame

the first line makes a list of all the text frames on the page on the header layer (this should be a list with only one item). the second line references the first (and only) item in the list — the heading text frame. and the third line grabs the ‘contents’ of that frame (the heading text) to use as the pdf filename. running that completed script will give you this result :
screen grab of generated pdfs
simple, eh?

the alternative method allows you to specify a filename for each page without that filename actually appearing anywhere on the page — the invisible script label. script labels are awesome and were the key to the functioning of the calendars script. a script label can be assigned to any page item, but for this example we’re going to label the heading text frames.

you open the script label panel under windows > utilities. select the frame you want to label — then just type the new label into the panel. once you’re done, deselect the frame — don’t just go to a different page, the script label won’t stick — and don’t hit ‘return’, as this will become part of the label :
screen grab of script label panel

providing you have only one labelled item on each page, you only need to add one extra line to that original basic script above :

set mgText to get (label of every page item of x whose label is not "")

giving you these pdfs :
screen grab of second set of pdfs

another variation will also add the export date to the pdf filenames — this is a good way to keep track of which version you’re up to. we just need to add two more lines :

set mgDate to do shell script "date '+%d-%m-%y'"

and

set mgText to mgText & "_" & mgDate

so the finished script would look like this :
screen grab of final script to export by script labels

and would create pdfs like this :
screen grab of final dated pdfs

ok, so there we have it — a few variations on the exporting-each-page-as-a-separate-pdf theme. hopefully, from this brief introduction, you can see that there are any number of ways to get the job done with applescript. there’s a solution out there for just about any workflow.

keep grunting.

macgrunt icon

InDesign scripting : lesson 33

lesson 32 started looking at how to export individual pages as separate PDFs. it looks like this topic has become popular … a fellow aussie with a passion for getting the most out of InDesign, with a particular focus on prepress, has also written about this, outlining a few solutions — Breaking up is hard to do…

as colmin8r points out, the script from lesson 32 has no user interface, so you can’t control how files are named. that’s what this lesson is all about — extending the script to give you more options. this is how scripts develop — get the basic functionality working, then expand the script to make it more user-friendly, or adaptable, or whatever.

here’s our base script — this time we’re exporting an interactive PDF, rather than using a print PDF preset — but apart from that, it’s the same as the script from lesson 32 :

tell application id "com.adobe.InDesign"
  set raster resolution of interactive PDF export preferences to one hundred forty four ppi
  set (export reader spreads of interactive PDF export preferences) to false
  set mgFolder to file path of active document
  set mgDocName to name of active document
end tell

tell application "Finder"
  if (exists folder "the pdfs" of folder mgFolder) is false then
    make folder at mgFolder with properties {name:"the pdfs"}
  end if
end tell

tell application id "com.adobe.InDesign"

  -- REST OF FUNCTIONALITY WILL GO IN HERE

  repeat with x from 1 to count pages of active document
    set mgPageName to name of page x of active document
    set page range of interactive PDF export preferences to mgPageName
    set mgFilePath to mgFolder & "the pdfs:" & mgDocName & mgPageName & ".pdf" as string
    tell active document
      export format interactive PDF to mgFilePath without showing options
    end tell
  end repeat
  display dialog "ALL DONE!" buttons {"OK"} default button 1
end tell

we’re going to give the user two options — shortening the existing filename by breaking it at the first space or underscore, and the option to add something else to the filename. the code for the dialog looks like this :

  set mgDialog to make dialog
  tell mgDialog
    tell (make dialog column)
      tell (make dialog row)
        make static text with properties {static label:"Where do you want to break the filename?"}
      end tell
      tell (make dialog row)
        set mgDelimiterButtons to make radiobutton group
        tell mgDelimiterButtons
          make radiobutton control with properties {static label:"first underscore", checked state:true}
          make radiobutton control with properties {static label:"first space"}
          make radiobutton control with properties {static label:"full stop", min width:290}
        end tell
      end tell
      tell (make dialog row)
        make static text with properties {static label:"current filename : " & mgDocName}
      end tell
      tell (make dialog row)
        make static text with properties {static label:" "}
      end tell
      tell (make dialog row)
        make static text with properties {static label:"Enter the text you'd like to append."}
      end tell
      tell (make dialog row)
        set mgSuffixField to make text editbox with properties {edit contents:"(can be blank)", min width:250}
      end tell
    end tell
  end tell
  set mgResult to show mgDialog

… and creates a user interface that looks like this :
screen grab of initial user interface
a couple of things to notice … we’ve also added the option of breaking the filename at the first full stop which, if you’re naming your files correctly, means not shortening the filename at all. the dialog also shows the existing filename (in this case “export separate pages_test_file.indd”) to make it easier for the user to make their selections.

the remainder of the code takes the information from the user interface and constructs a new filename to use when saving the PDFs :

  if mgResult is true then
    set mgDelimiterButton to selected button of mgDelimiterButtons
    if mgDelimiterButton is 0 then
      set mgDelimiter to "_"
    else if mgDelimiterButton is 1 then
      set mgDelimiter to " "
    else if mgDelimiterButton is 2 then
      set mgDelimiter to "."
    end if
    
    set text item delimiters of AppleScript to mgDelimiter
    set mgDocName to text item 1 of mgDocName
    set text item delimiters of AppleScript to ""
    
    set mgSuffix to edit contents of mgSuffixField as string
    if mgSuffix is "(can be blank)" then
      set mgSuffix to ""
    end if
    set mgDocName to (mgDocName & "_" & mgSuffix)
    destroy mgDialog
  else
    error number -128
  end if

two things to note here. we’ve added some error handling just in case the user inadvertently leaves “(can be blank)” in the text field of the user interface — we don’t want that to become part of the filename, so we change it to “” (that is, nothing) instead. also, we’re using an underscore to join the shortened filename and the suffix.

hopefully it’s pretty clear how this filenaming works. as an example — if we start with the filename “export separate pages_test_file.indd”, break it at the first space and add the suffix “concepts”, our resulting PDF filenames will be “export_concepts1.pdf”, “export_concepts2.pdf”, etc.

ok, that’s one way you could do it — but you could also make it more complex again by giving the user the option to break the filename in a different place. of course, more complex options mean more complex code. so this :

  set mgDialog to make dialog with properties {name:"Where do you want to break the filename?"}
  tell mgDialog
    tell (make dialog column)
      set mgPlaceButtons to make radiobutton group
      tell mgPlaceButtons
        make radiobutton control with properties {static label:"first", checked state:true}
        make radiobutton control with properties {static label:"second"}
        make radiobutton control with properties {static label:"third", min width:100}
      end tell
    end tell
    tell (make dialog column)
      set mgDelimiterButtons to make radiobutton group
      tell mgDelimiterButtons
        make radiobutton control with properties {static label:"space", checked state:true}
        make radiobutton control with properties {static label:"underscore"}
        make radiobutton control with properties {static label:"full stop", min width:130}
      end tell
    end tell
    tell (make dialog column)
      tell (make dialog row)
        make static text with properties {static label:"current filename : "}
      end tell
      tell (make dialog row)
        make static text with properties {static label:mgDocName}
      end tell
      tell (make dialog row)
        make static text with properties {static label:" ", min width:300}
      end tell
      tell (make dialog row)
        make static text with properties {static label:"Enter the text you'd like to append."}
      end tell
      tell (make dialog row)
        set mgSuffixField to make text editbox with properties {edit contents:"(can be blank)", min width:250}
      end tell
    end tell
  end tell
  set mgResult to show mgDialog

is what you need to create a user interface that looks like this :
screen grab of revised user interface

and the rest of the code is more complex too. this time we’re using the chosen break character to join the filename to the suffix (rather than forcing it to be an underscore) :

  if mgResult is true then
    set mgPlaceButton to selected button of mgPlaceButtons
    if mgPlaceButton is 0 then
      set mgPlace to "1"
    else if mgPlaceButton is 1 then
      set mgPlace to "2"
    else if mgPlaceButton is 2 then
      set mgPlace to "3"
    end if
    set mgDelimiterButton to selected button of mgDelimiterButtons
    if mgDelimiterButton is 0 then
      set mgDelimiter to " "
    else if mgDelimiterButton is 1 then
      set mgDelimiter to "_"
    else if mgDelimiterButton is 2 then
      set mgDelimiter to "."
    end if
    
    set text item delimiters of AppleScript to mgDelimiter
    try
      set mgDocName to text items 1 thru (mgPlace + 1) of mgDocName
      set mgDocName to text items 1 thru mgPlace of mgDocName
    on error
      display dialog "come on dude — that's not possible" & return & "there are not " & mgPlace & " \"" & mgDelimiter & "\" in the filename" & return & return & "have another go" buttons "sorry"
      error number -128
    end try
    set mgDocName to mgDocName as string
    set text item delimiters of AppleScript to ""
    
    set mgSuffix to edit contents of mgSuffixField as string
    if mgSuffix is "(can be blank)" or mgSuffix is "" then
      set mgSuffix to ""
      set mgDocName to (mgDocName & mgSuffix)
    else
      set mgDocName to (mgDocName & mgDelimiter & mgSuffix)
    end if
    destroy mgDialog
  else
    error number -128
  end if

so this time — if we start with the filename “export separate pages_test_file.indd”, break it at the second space and add the suffix “concepts”, our resulting PDF filenames will be “export separate concepts1.pdf”, “export separate concepts2.pdf”, etc.

notice in the above code we’ve added some error handling to make sure the user’s choices make sense. that is, if they choose to break the filename at the third space, and there are not three spaces in the filename, rather than the script simply failing, they’ll get a message stating why it’s not going to work :
screen grab of error message presented to user

and, of course, you can keep on expanding the script until you have as many different options as suits your needs.

the next lesson will look at a couple of other ways we could approach the naming of these separate page PDFs — automatically generating filenames based on data already existing in the document.

until then, keep grunting.

macgrunt icon

InDesign scripting : lesson 32

there’s quite a farcical discussion going on over at the InDesign forum — Is there really no way to export PDFs as separate pages? as is so often the case in these forums, a person asks HOW to do something and then there’s an extended, often heated, discussion about WHY you would/wouldn’t or should/shouldn’t do it that way.

but the argy-bargy is unnecessary because there are some truly legitimate workflows that would benefit from this capability — like the guy at comment 39 — and because exporting each InDesign page as a separate PDF is really easy with Applescript.

today we’ll be looking at a simplified version of the script from lessons 11 and 12. we start by collecting the filename and file path of the active document. then we shorten the filename to exclude the extension — so “this file.indd” becomes “this file” (mgShortName):

tell application id "com.adobe.InDesign"
  set mgFolder to file path of active document
  set mgName to name of active document
  set text item delimiters of AppleScript to {"."}
  set mgShortName to text item 1 of mgName
  set text item delimiters of AppleScript to ""
end tell

next we’ll create a subfolder for the pdfs to be saved into. you do this through the finder by first checking if the subfolder already exists and, if not, creating it. we’re calling this subfolder “the pdfs” and it will be created in the same folder as the indesign file :

tell application "Finder"
  if (exists folder "the pdfs" of folder mgFolder) is false then
    make folder at mgFolder with properties {name:"the pdfs"}
  end if
end tell

then it’s just a matter of a simple repeat loop, cycling through each page in the document. we’re using the page number (name of page) as part of the filename so, using the example above, we’ll end up with “this file_1.pdf”, “this file_2.pdf”, etc. and we complete the script with a simple dialog to let us know when it has done its thing :

tell application id "com.adobe.InDesign"
  repeat with x from 1 to count pages of active document
    set mgPageName to name of page x of active document
    set page range of PDF export preferences to mgPageName
    set mgFilePath to mgFolder & "the pdfs:" & mgShortName & "_" & mgPageName & ".pdf" as string
    tell active document
      export format PDF type to mgFilePath using "macgrunt offset" without showing options
    end tell
  end repeat
  display dialog "ALL DONE!" buttons {"OK"} default button 1 giving up after 2
end tell

notice that when we specify mgFilepath we add a colon to “the pdfs” — this is what designates it as a folder. the full file path might be something like this “Macintosh HD:Users:macgrunt:Documents:the pdfs:this file_1.pdf” — this shows a hierarchy of five folders — everything after that last colon is the name of the file. so, if we didn’t add the colon after “the pdfs” the filename would have been “the pdfsthis file_1.pdf” (hopefully that makes sense).
note also that “macgrunt offset” is the name of the PDF export preset — you would need to substitute your own preset name here.

so that’s the basic functionality for exporting every page as a separate PDF. copy those three sections into a single script in applescript editor and you’re away. there are a bunch of macgrunt lessons showing other PDF export workflows and considerations — just enter “export pdf” up there in the search field.

the next lesson will look at a couple of other, more complex, ways we could approach the naming of these separate page PDFs.

until then, keep grunting.

macgrunt icon

InDesign scripting : lesson 31

in lesson 30 we looked at an applescript to change rows of a particular height to a new height throughout an entire InDesign table. here’s an example of slightly more complex table formatting.

no doubt you would use table and cell styles when setting up your own tables — to assist with formatting changes further down the track. but sometimes you need to work on tables that other, less diligent InDesign users have set up. and if you’re doing that on a regular basis, or if the tables are extensive, it makes sense to automate the tedium.

we’ll look again at the table from the last lesson :
screen grab of table before formatting

in this table, all cells have the same settings :
screen grab of control panel showing table settings

but now we want the reversed row heights to be a little wider and the blank rows to be narrower. first we need to change all the rows to a specific height before working on the other rows. to do this we change the ‘at least’ specifier to ‘exactly’ by changing auto grow to false :

tell application id "com.adobe.InDesign"
  tell active document
    tell table 1 of selection
      set auto grow of every row to false
      set height of every row to 5
      -- rest of script to go here
    end tell
  end tell
end tell

then we can use the cell fill colour to address the reversed rows only :

set height of (every row whose name of fill color is "C=0 M=100 Y=100 K=50") to 6.5

we need to use a different tactic for the blank rows. here’s one way — address every row that comes before a reversed row :

repeat with x in (every row whose name of fill color is "C=0 M=100 Y=100 K=50")
  set mgName to name of x
  try
    set height of row (mgName - 1) to 2
  end try
end repeat

the ‘name’ of a row is its number — so the first row in a table is row 1. that’s why we need the try statement — the first reversed row is row 1 and there is no row 0 to change to a height of 2 — so the script would throw an error without that try.

if we run that script the table will look like this :
screen grab of table after initial script run

the only remaining problem, as the observant will notice, is that there is at least one cell (and probably more) which is now too small and has overset text. an extra line in the script will fix that :

set height of every cell whose overflows is true to 9

the compiled script is short and simple :
screen grab of compiled script

… and the completed table looks like this :
screen grab of completed table

this is just a taster for what can be done with table formatting through applescript. whether or not you end up using scripting with your own tables depends on your workflow, how big your tables are, how often you work with tables, etc, etc. sometimes table are just too small to justify the time it takes to write or edit a script. but table scripting could be another powerful tool in your production arsenal — anything to minimise the monkey-work.

macgrunt icon