Here is the script.
CAUTION :
it's dedicated to OS X 10.7 and higher.
it treat only the body text.
--{code}
--[SCRIPT split_Pages_doc]
(*
Première formule:
Enregistrer le script en tant que Script : split_Pages_doc.scpt
déplacer le fichier ainsi créé dans le dossier
<VolumeDeDémarrage>:Utilisateurs:<votreCompte>:Bibliothèque:Scripts:Applications :Pages:
Il vous faudra peut-être créer le dossier Pages et peut-être même le dossier Applications.
Si Pages est au premier plan, aller au menu Scripts , choisir Pages puis choisir “split_Pages_doc”
Sélectionner le document Pages à traiter.
Seconde formule :
Enregistrer le script comme application.
L'exécuter par un double clic ou glisser déposer l'icône du document à traiter sur celle du script-application.
Le script ouvre le document sélectionné, le duplique puis ferme l'original.
Il extrait de la réplique les blocs de texte délimités par les paragraphes dotés du style Sous-section 2
et les enregistre dans des fichiers différents.
--=====
L’aide du Finder explique:
L’Utilitaire AppleScript permet d’activer le Menu des scripts :
Ouvrez l’Utilitaire AppleScript situé dans le dossier Applications/AppleScript.
Cochez la case “Afficher le menu des scripts dans la barre de menus”.
Sous 10.6.x,
aller dans le panneau “Général” du dialogue Préférences de l’Éditeur Applescript
puis cocher la case “Afficher le menu des scripts dans la barre des menus”.
--=====
First scheme:
Save the script as a Script: split_Pages_doc.scpt
Move the newly created file into the folder:
<startup Volume>:Users:<yourAccount>:Library:Scripts:Applications:Pages:
Maybe you would have to create the folder Pages and even the folder Applications by yourself.
If Pages is at front, go to the Scripts Menu, choose Pages, then choose “split_Pages_doc”
Select the Pages's document to treat.
Alternate scheme
Save the script as an application
Run it thru a double-click or drag & drop a Pages document's icon on the application-script one's.
The script opens the selected document, duplicate it then close the original.
It extract from the replicate the blocks of text delimited by the paragraphs wearing the style Heading 2
and save them in different files.
--=====
The Finder’s Help explains:
To make the Script menu appear:
Open the AppleScript utility located in Applications/AppleScript.
Select the “Show Script Menu in menu bar” checkbox.
Under 10.6.x,
go to the General panel of AppleScript Editor’s Preferences dialog box
and check the “Show Script menu in menu bar” option.
--=====
Yvan KOENIG (VALLAURIS, France)
2011/12/23
*)
--=====
(*
1. Asks the user which Pages Document to open
2. Ask the user where they want to save the resulting files (which will follow the naming convention of originalFilename + "_" + currentHeadingTitle + ".pages")
3. Look at the Table of Contents.
4. Next, take each section that begins with a Level 2 heading, select its text (including the heading itself), then copy that text and paste it into a new Pages document. Save the file as per the specifications in step (2).
5. Repeat, until there are no more Level 2 headings to process.
*)
--=====
property types_valides : {"com.apple.iwork.pages.pages", "com.apple.iWork.pages.sffpages"}
--=====
on run (*
lignes exécutées si on double clique sur l'icône du script application
• lines executed if one double click the application script's icon *)
local monAccroche, acceptables
tell application "System Events"
if my parleAnglais() then
set monAccroche to "Choose a Pages document"
else
set monAccroche to "Choisir un document Pages"
end if -- parleAnglais
if 5 = (system attribute "sys2") then (*
it's Mac OS X 10.5.x with a bug with Choose File *)
set acceptables to {}
else (*
if Mac Os X 10.4.x *)
set acceptables to my types_valides
end if -- 5 = (system…
end tell
my commun(choose filewith promptmonAccrocheof typeacceptables without invisibles) (* un alias *)
end run
--=====
on open (sel) (*
sel contient une liste d'alias des élémentsqu'on a déposés sur l'icône du script (la sélection)
• sel contains a list of aliases of the items dropped on the script's icon (the selection) *)
my commun(item 1 of sel) (* an alias *)
end open
--=====
on commun(leCheminAlias)
local leCheminTexte, nomDuDocument, dossierDuDocument, typeID, nomRaccourci
local STYLE_Heading2_loc, nbd, nomDuplicata, index_des_paragraphes_avec_style, i, dernier
local p, off7, titrePara, nouveauNom, nouveauChemin, error_message, error_number
if 7 is not (system attribute "sys2") then
if my parleAnglais() then
error "This script requires OS X 10.7 or higher !"
else
error "Ce script requiert OS X 10.7 ou plus récent !"
end if -- my parleAnglais()
end if
my activateGUIscripting()
set leCheminTexte to leCheminAlias as text
(*
Extract some informations about the document *)
tell application "System Events" to tell disk item leCheminTexte
set nomDuDocument to name
set dossierDuDocument to path of container
try
set typeID to (type identifier) as text
on error
set typeID to "????" (* Here if we dropped a folder *)
end try
end tell -- System Events
(*
Must check that it's a Pages document in case we dropped items on the application-script *)
if typeID is not in my types_valides then
if my parleAnglais() then
error "“" & leCheminTexte & "” is not a Pages document !"
else
error "«" & leCheminTexte & "» n’est pas un document Pages !"
end if -- my parleAnglais()
end if -- typeID
(*
Prepare a name deprieved of the extension to build later new file names *)
if leCheminTexte ends with ".pages" then
set nomRaccourci to text 1 thru -7 of nomDuDocument
else
set nomRaccourci to nomDuDocument
end if
(*
Extract the localized name of the 'Level 2 heading' style *)
set STYLE_Heading2_loc to my getLocalizedStyleName("Pages", "Blank.template", "STYLE_Heading 2")
tell application "Pages"
set nbd to countdocuments
openleCheminAlias
repeat while count documents = nbd
--
end repeat
(*
We are sure that the document is open *)
set nbd to nbd + 1
(*
Duplicate the document so we will not change the original document. *)
my selectmenu("Pages", 3, 10)
repeat while count documents = nbd
--
end repeat
(*
We are sure that the duplicate exists *)
set nomDuplicata to name of document 1
(*
We may drop the original document *)
closedocumentnomDuDocument
(*
To be sure that the duplicate document is at front , trigger its menu item in the Windows menu *)
my selectmenu("Pages", 9, nomDuplicata)
set index_des_paragraphes_avec_style to {}
tell body text of document nomDuplicata
(*
Loop among paragraphs to get the index of our styled ones. *)
repeat with i from 1 to count of paragraphs
if name of paragraph style of paragraphi is STYLE_Heading2_loc then copy i to end of index_des_paragraphes_avec_style
end repeat
end tell -- body text…
end tell -- Pages
(*
Main loop starting from the end of the document *)
try
tell application "Pages"
set dernier to -1
repeat with i from (count of index_des_paragraphes_avec_style) to 1 by -1
set p to itemi of index_des_paragraphes_avec_style
tell body text of document nomDuplicata
tell paragraph p
set off7 to get character offset
set titrePara to contents
end tell
select (characters (off7 + 1) thru dernier)
set dernier to off7 - 1
my raccourci("Pages", "x", "c")
end tell -- document nomDuplicata
(*
Build the name of the new document from the content of the styled paragraph.
CAUTION : must take care to remove forgotten characters *)
set nouveauNom to my remplace(nomRaccourci & "_" & titrePara & ".pages", {"/", ":"}, "_")
set nouveauChemin to my makeNewIworkDoc("Pages", nouveauNom, dossierDuDocument)
tell document nouveauNom
(*
Paste in the new document *)
my raccourci("Pages", "v", "c")
end tell --document nouveauNom
(*
Close the document to save it *)
closedocumentnouveauNom
end repeat
(*
It remain only the TOC so we may drop the document. *)
closedocumentnomDuplicata without saving
end tell -- Pages
on error error_messagenumbererror_number
my nettoie()
if error_number is not -128 then my affiche(error_message)
end try
end commun
--=====
on affiche(msg)
tell application "Finder"
activate
if my parleAnglais() then
display dialogmsgbuttons {"Cancel"} default button 1 giving up after 120
else
display dialogmsgbuttons {"Annuler"} default button 1 giving up after 120
end if -- parleAnglais()
end tell -- application
end affiche
--=====
on decoupe(t, d)
local l
set AppleScript's text item delimiters to d
set l to text items of t
set AppleScript's text item delimiters to ""
return l
end decoupe
--=====
on recolle(l, d)
local t
set AppleScript's text item delimiters to d
set t to l as text
set AppleScript's text item delimiters to ""
return t
end recolle
--=====
(*
replaces every occurences of d1 by d2 in the text t
*)
on remplace(t, d1, d2)
local oTIDs, l
set oTIDs to AppleScript's text item delimiters
set AppleScript's text item delimiters to d1
set l to text items of t
set AppleScript's text item delimiters to d2
set t to l as text
set AppleScript's text item delimiters to oTIDs
return t
end remplace
--=====
on parleAnglais()
local z
try
tell application "Pages" to set z to localized string "Cancel"
on error
set z to "Cancel"
end try
return (z is not "Annuler")
end parleAnglais
--=====
on activateGUIscripting()
(* to be sure than GUI scripting will be active *)
tell application "System Events"
if not (UI elements enabled) then set (UI elements enabled) to true
end tell
end activateGUIscripting
--=====
(*
==== Uses GUIscripting ====
*)
(*
This handler may be used to 'type' text, invisible characters if the third parameter is an empty string.
It may be used to 'type' keyboard raccourcis if the third parameter describe the required modifier keys.
I changed its name « shortcut » to « raccourci » to get rid of a name conflict in Smile.
*)
on raccourci(a, t, d)
local k
tell applicationa to activate
tell application "System Events" to tell application process a
set frontmost to true
try
t * 1
if d is "" then
key codet
else if d is "c" then
key codetusing {command down}
else if d is "a" then
key codetusing {option down}
else if d is "k" then
key codetusing {control down}
else if d is "s" then
key codetusing {shift down}
else if d is in {"ac", "ca"} then
key codetusing {command down, option down}
else if d is in {"as", "sa"} then
key codetusing {shift down, option down}
else if d is in {"sc", "cs"} then
key codetusing {command down, shift down}
else if d is in {"kc", "ck"} then
key codetusing {command down, control down}
else if d is in {"ks", "sk"} then
key codetusing {shift down, control down}
else if (d contains "c") and (d contains "s") and d contains "k" then
key codetusing {command down, shift down, control down}
else if (d contains "c") and (d contains "s") and d contains "a" then
key codetusing {command down, shift down, option down}
end if
on error
repeat with k in t
if d is "" then
keystroke (k as text)
else if d is "c" then
keystroke (k as text) using {command down}
else if d is "a" then
keystrokekusing {option down}
else if d is "k" then
keystroke (k as text) using {control down}
else if d is "s" then
keystrokekusing {shift down}
else if d is in {"ac", "ca"} then
keystroke (k as text) using {command down, option down}
else if d is in {"as", "sa"} then
keystroke (k as text) using {shift down, option down}
else if d is in {"sc", "cs"} then
keystroke (k as text) using {command down, shift down}
else if d is in {"kc", "ck"} then
keystroke (k as text) using {command down, control down}
else if d is in {"ks", "sk"} then
keystroke (k as text) using {shift down, control down}
else if (d contains "c") and (d contains "s") and d contains "k" then
keystroke (k as text) using {command down, shift down, control down}
else if (d contains "c") and (d contains "s") and d contains "a" then
keystroke (k as text) using {command down, shift down, option down}
end if
end repeat
end try
end tell
end raccourci
--=====
(*
my selectMenu("Pages",5, 12)
==== Uses GUIscripting ====
*)
on selectmenu(theApp, mt, mi)
activateapplicationtheApp
tell application "System Events" to tell application process theApp to tell menu bar 1 to ¬
tell menu bar itemmt to tell menu 1 to clickmenu itemmi
end selectmenu
(* {
(01) "Nouveau",
(02) "Créer à partir de la liste de modèles…",
(03) missing value,
(04) "Ouvrir…",
(05) "Ouvrir un document récent",
(06) missing value,
(07) "Fermer",
(08) "Tout fermer",
(09) "Enregistrer une version",
(10) "Dupliquer",
(11) "Faire revenir le document à une version précédente...",
(12) "Exporter…",
(13) missing value,
(14) "Réduire la taille du fichier",
(15) missing value,
(16) "Enregistrer comme modèle…",
(17) missing value,
(18) "Format d’impression…",
(19) "Imprimer…"
}*)
--=====
(*
my selectSubMenu("Pages",6, 4, 26)
==== Uses GUIscripting ====
*)
on selectSubMenu(theApp, mt, mi, ms)
activateapplicationtheApp
tell application "System Events" to tell application process theApp to tell menu bar 1 to ¬
tell menu bar item mt to tell menu 1 to tell menu item mi to tell menu 1 to click menu item ms
end selectSubMenu
--=====
(*
Example
set UNTITLED_loc to my getLocalizedStyleName("Pages", "STYLE_Heading 8")
Requires :
getLocalizenomDuDocument()
*)
on getLocalizedStyleName(theApp, tName, x)
local path2app, p2bndl
tell applicationtheApp to activate
tell application "System Events"
set path2app to (application file of application processtheApp as text)
set p2bndl to path2app & "Contents:Resources:Templates:" & tName & ":Contents:Resources:"
return my getLocalizenomDuDocument(theApp, x, p2bndl)
end tell
end getLocalizedStyleName
--=====
on getLocalizenomDuDocument(a, x, f)
tell application a to return localized string x from table "Localizable" in bundle file f
end getLocalizenomDuDocument
--=====
(*
Creates a new iWork document from the Blank template,
saves it and returns its pathname.
example:
set nouveauChemin to my makeNewIworkDoc(theApp, docName, folderPath)
*)
on makeNewIworkDoc(the_app, doc_name, doc_folder)
local maybe, nb_doc, path_to_the_App, path_to_the_doc
if the_app is "Pages" then
tell application "Pages"
set nb_doc to count of documents
makenewdocumentwith properties {template name:item 1 of templates}
end tell
else if the_app is "Numbers" then
tell application "System Events" to set maybe to the_app is in title of every application process
if not maybe then tell application the_app to activate
tell application "System Events"
set path_to_the_App to get application file of application processthe_app
end tell
tell applicationthe_app
set nb_doc to count of documents
open ((path_to_the_App as text) & "Contents:Resources:Templates:Blank.nmbtemplate:")
end tell
else
if my parleAnglais(the_app) then
error "The application “" & the_app & "“ is not accepted !"
else
error "l’application « " & the_app & " » n’est pas gérée !"
end if
end if
if doc_name does not end with "." & the_app then set doc_name to doc_name & "." & the_app
if doc_folder ends with ":" then
set path_to_the_doc to doc_folder & doc_name
else
set path_to_the_doc to doc_folder & ":" & doc_name
end if
tell applicationthe_app
repeat until (count of documents) > nb_doc
delay 0.1
end repeat
savedocument 1 infilepath_to_the_doc
end tell -- the_App
return path_to_the_doc as alias
end makeNewIworkDoc
--=====
-- [/SCRIPT]
--{code}
Yvan KOENIG (VALLAURIS, France) vendredi 23 décembre 2011 19:12:54
iMac 21”5, i7, 2.8 GHz, 12 Gbytes, 1 Tbytes, mac OS X 10.6.8 and 10.7.2
My iDisk is : <http://public.me.com/koenigyvan>
Please : Search for questions similar to your own before submitting them to the community