Automating Adobe InDesign 2019 - AppleScript


Document from Template With Adjustments

Tuesday, July 02, 2019

Create Document from Template

One of my most used utility scripts is one that creates a document from a template. Templates are saved in a folder named "Templates" (what else?) inside InDesign's applicatiom folder. The script is used so often that it is assigned a keyboard shortcut (Option + Shift + N).

Document From Template Chosen

(*Presents user a list of templates found in Templates folder for application. 
Creates document from template chosen.*)
try
   set docRef to docFromTemplateChosen()
on error errStr
   activate
   display alert errStr
end try

on docFromTemplateChosen()
   tell application "Adobe InDesign CC 2019"
      if modal state is true then
	error ("Please close dialogs and try again")
      end if
      set appPath to file path as string
      set templatePath to appPath & "Templates:"
      set templateChoice to my getTemplate(templatePath)
	set docRef to open file (templatePath & templateChoice)
      end tell
      return docRef
end docFromTemplateChosen

on getTemplate(templatePath)
   set templateNames to list folder templatePath without invisibles
   set fileChoice to choose from list templateNames without multiple selections allowed
   if fileChoice is not false then
      set templateChoice to item 1 of fileChoice
   else
      error ("Requires choice of template")
   end if
   return templateChoice
end getTemplate 

New With CC 2019

Now, with InDesign CC 2019, it is possible to do much more when creating a new document using a template. You can now change the document size, orientation, margins, bleed, and even options for changing font size. This means that your templates can now control all of the document styling with an unlimited variety of document sizes, margins, and so on. InDesign provides a number of ways to access this capability manually:

  • From the File menu select Document Setup, and click the Adjust Layout button.
  • From the File menu select Adjust Layout.
  • Click the Adjust Layout button on the Properties panel.
  • Each of these options opens the Adjust Layout dialog

    shows Adjust Layout dialog...Adjust Layout Dialog

    As you can see, this dialog is fairly involved. Suppose you just want to change the size of the document and maybe its margins. For this we will walk through the creation of a script that simplifies the process. First your script will need to set preferences for adjusting the document layout.

    Adjust Layout Preferences

    Adjust layout preferences are set at the document level with enable adjust layout set to false by default. Other adjust layout preferences that can be set are:

    • enable auto adjust margins to true - margins will change proportionally if this preference is set to true.
    • allow font size and leading adjustment - if true, allows font sizes and leading to adjust
    • allow locked objects to adjust - If true, allows locked objects or objects on locked layers to be adjusted
    • maximum font size - in points, sets restriction on maximum font size
    • minimum font size - in points, sets restriction on minimum font size

    Of particular interest is allow locked objects to adjust. This presents a host of possibilities in setting up your template. For all  objects in your template you don't want altered, simply lock or place them on locked layers. Set allow locked object to adjust to false.

    For our demonstration script, all preferences with exception of document size and margins will be set as default values. The first step of the script will adjust the layout for an existing document.

    Adjust Layout

    set newWid to "8 in"
    set newHgt to "6 in"
    set marginList to {"72 pt", "72 pt", "36 pt", "36 pt"}
    set maxSize to 36.0 --units are in points decimal
    set minSize to 12.0 --units are in points decimal
    tell application "Adobe InDesign CC 2019"
       tell document 1
    	tell adjust layout preferences
    	   set enable adjust layout to true --class pEAL of class ALPO
    	   set enable auto adjust margins to true
    	   set allow locked objects to adjust to false
    	   set allow font size and leading adjustment to true
    	   set impose font size restriction to true
    	   set maximum font size to maxSize
    	   set minimum font size to minSize
    	end tell
    	copy marginList to {tp, lft, bot, rgt}
    	adjust layout adopt to {width:newWid, height:newHgt, ¬
    top margin:tp, left margin:lft, bottom margin:bot, right margin:rgt}
       end tell
    end tell

    Apply to Template

    With the code for setting layout adjustment above, we can add it to code from our Document From Template Chosen script.

    Template With Layout Adjustment

    set newWid to "8.5 in"
    set newHgt to "11 in"
    set marginList to {"72 pt", "72 pt", "36 pt", "36 pt"}
    try
       tell application "Adobe InDesign CC 2019"
    	if modal state is true then
    	   error ("Please close dialogs and try again")
    	end if
    	set appPath to file path as string
    	set templatePath to appPath & "Templates:"
    	set templateChoice to my getTemplate(templatePath)
    	set docRef to open file (templatePath & templateChoice)
    	tell docRef
    	   --set adjust layout preferences
    	   tell adjust layout preferences
    		set enable adjust layout to true 
    		set allow locked objects to adjust to false
                    set allow font size and leading adjustment to false
    	   end tell
    	   copy marginList to {tp, lft, bot, rgt}
    	   adjust layout adopt to {width:newWid, height:newHgt, ¬
    top margin:tp, left margin:lft, bottom margin:bot, right margin:rgt}
    	end tell
       end tell
    on error errStr
       activate
       display alert "Error: " & errStr
    end try
    
    (*Gives user choice of templates in Templates folder; returns choice or error*)
    on getTemplate(templatePath)
       set templateNames to list folder templatePath without invisibles
       set fileChoice to choose from list templateNames without multiple selections allowed
       if fileChoice is not false then
    	set templateChoice to item 1 of fileChoice
       else
    	error ("Requires choice of template")
       end if
       return templateChoice
    end getTemplate

    Use Custom Dialog

    Of course you will not want all of the document adjust settings to be hard coded to the script. Instead, you will want to create a custom dialog to get these settings from the user. As you know, custom dialogs are not hard to write but they can take a fairly extensive amount of code. In the script following, we have started the dialog for you but it only allows the choice for the template. You will need to add code to get the settings for the new page width (defaultWid) and the new page height (defaultHgt). Also if you don't want margins adjusted automatically, you will need to add the ability to define top margin, left margin, bottom margin, and right margin. If you have problems, we are demonstrating this script on our Feature page (yourscriptdoctor.com/Feature). You can download the entire code for the demonstration script from there.

    DocFromTemplate_AdjustWDialog

    set enableAuto to false
    set defaultWid to "8 in" --default width
    set defaultHgt to "10 in" --default height
    set marginSets to {"72pt", "36pt", "36pt", "36pt"}
    set marginRec to {}
    try
       tell application "Adobe InDesign CC 2019"
    	if modal state is true then
    	   error ("Please close dialogs and try again")
    	end if
    	set templatePath to (file path as string) & "Templates:"
    	set adjustList to my customDialog("New Document Adjustments", true, templatePath)
    	copy adjustList to {templateChoice, docSizeList, marginSets}
    	set docRef to open file (templatePath & templateChoice)
    	if marginSets is {} then
    	   set enableAuto to true
    	else
    	   copy marginSets to {tp, lft, bot, rgt}
    	   set marginRec to {top margin:tp, left margin:lft, bottom margin:bot, right margin:rgt}
    	end if
    	--set adjust layout preferences
    	tell adjust layout preferences of docRef
    	   set enable adjust layout to true 
    	   set allow locked objects to adjust to false
    	   set enable auto adjust margins to enableAuto
    	   set allow font size and leading adjustment to false
    	end tell
    	--adjust the document
    	if docSizeList = {} then
    	   set layoutRec to {width:defaultWid, height:defaultHgt} & marginRec
    	else
    	   set layoutRec to {width:item 1 of docSizeList, height:item 2 of ocSizeList} & marginRec
    	end if
    	tell docRef
    	   adjust layout adopt to layoutRec
    	end tell
    	--save the document
    	set savePath to choose file name with prompt "Select file and folder for save"
    	if savePath as string does not end with ".indd" then
    	   set savePath to (savePath as string) & ".indd"
            end if
    	save docRef to savePath without force save
       end tell
    on error errStr
       activate
       display alert "Error: " & errStr
    end try
    
    (*Dialog for Adjust Layout settings including template choice, document size and margins*)
    on customDialog(dlgName, cancelIt, templatePath)
       set templateNames to list folder templatePath without invisibles
       tell application "Adobe InDesign CC 2019"
    	activate
    	set origLevel to user interaction level of script preferences
    	set user interaction level of script preferences to interact with all
    	set dlgRef to make dialog with properties {name:dlgName, can cancel:cancelIt}
    	tell dlgRef
    	   set dlgColumn to make dialog column
    	   tell dlgColumn
    	      tell (make dialog row)
    		 make static text with properties {static label:"Select Template:"}
    		 set fileDrop to make dropdown with properties ¬
    {string list:templateNames, selected index:0, min width:144}
    	       end tell--row	
    	     end tell --dlgColumn 
    	 end tell --dlgRef				
    	 set userResponse to show dlgRef
    	 if userResponse = true then
    	    set docSizeList to {}
    	    set marginSets to {}
    	    set fileName to item ((selected index of fileDrop) + 1) of templateNames
    	 end if
    	 destroy dlgRef
    	 set user interaction level of script preferences to origLevel
    	 if userResponse = false then
    	    error "User cancelled"
    	 end if
       end tell
       return {fileName, docSizeList, marginSets}
    end customDialog 

    Onward and Upward

    You may want to make your script even more robust by adding the option to adjust font size with minimum and maximum font size restrictions (see Adjust Layout script above).

    Disclaimer:
    Scripts provided are for demonstration and educational purposes. No representation is made as to their accuracy or completeness. Readers are advised to use the code at their own risk.

    Trackback Link
    http://www.yourscriptdoctor.com/BlogRetrieve.aspx?BlogID=18424&PostID=1529367&A=Trackback
    Trackbacks
    Post has no trackbacks.

    Recent Posts


    Tags

    find change options Library Folder Image Events start paragraph bookmarks Enabling Groups handlers Buttons Export to PDF Adding Captions primary text frame Placing images XML tags Checkbox Control rest XML structure Find Text Apply Object Style coordinates Text Style Mapping static alignment dialog Excel Next Style move file text item delimiters time Editbox selection file info giving up after entire path Script Preferences paragraph styles user interaction level object styles table styles Clearing Overrides Read text file as list active spread XML InDesign template lists of lists place point next text frame Styling Text reference to script folder Previous text frame sort list auto tag Create Document date objects do script info for map tags to styles StandardAdditions CALS tables measurement editboxes Document Presets tabs Write to File import XML image metadata Image Placement import styles Keyboard Shortcuts intent master spread automated workflow live bounds Script panel Place text Check for Styles radiobutton control text import preferences Document from Template Nested Repeat Loops Adjust Layout measurements stacking order text editbox Script Library Multi-state objects lists Radiobutton Group Choose from list Combobox tab list GREP Find by Attribute grid Document stylesheets draw from center import text Templates Create Text Frame convert to text choose file name file paths page items script templates Choose file Chaining Paragraph Styles dropdowns Custom Dialog try/on error Autoflow repeat loops fit integer editboxes Repeat With Border Panel Character Styles threaded text frames rest of list random number Change Text Duplicate

    Archive