As far as I know, the 1st step is complicated and I’m not sure that it may be achieved.
There is no provision to drive this feature thru plain AppleScript.
Everything would be driven by GUIScripting.
As I’m curious, I will try to do the trick.
For other steps I have all the tools allowing to do the trick.
(a) two ways to split the result of the merge task in separate PDFs.
(b) script to create mails with embedded attachment. (I will have to retrieve this one).
First way to split.
This one use plain AppleScript.
To achieve this goal, it duplicate the Pages document created by the merge feature,
remove every sections minus one,
save the one section file in a PDF.
--{code}
--[SCRIPT splitMergedFile]
(*
Enregistrer le script en tant que Script : splitMergedFile.scpt
déplacer le fichier ainsi créé dans le dossier
<VolumeDeDémarrage>:Users:<votreCompte>:Library:Scripts:Applications:Pages:
Il vous faudra peut-être créer le dossier Pages et peut-être même le dossier Applications.
Ouvrir le document Mise en pages résultant d'une fusion de données
menu Scripts > Pages > splitMergedFile
crée un fichier PDF pour chaque section du document.
--=====
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".
--=====
Save the script as a Script: splitMergedFile.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.
Open the Layout document build by a Merge session.
menu Scripts > Pages > splitMergedFile
create a PDF for every embedded section.
--=====
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.
--=====
Yvan KOENIG (VALLAURIS, France)
2010/05/11
*)
--=====
(*
Some global constants
*)
property targetFolderName : "Merged pages or sections"
property folderOnDesktop : true
(*
true = stores the PDFs in a folder on the Desktop
false = stores the PDFs in a subfolder of the Documents folder
*)
property useDateStamp : false
(*
true = inserts a dateTimeStamp in the names of PDFs
false = doesn't insert a dateTimeStamp in the names of PDFs
*)
--=====
on run
tell application "Pages"
set dName to name of document 1
tell document 1
set maybe to (get body text) is missing value
end tell
end tell -- Pages
if not maybe then
if my parleAnglais() then
error "The document "" & dName & "" is not a Layout one !"
else
error """ & dName & "" n'est pas un document Mise en page !"
end if -- parleAnglais.
end if -- not maybe.
(*
Build some constants
(1) Prepare a folder to store the PDF reports
*)
if folderOnDesktop then
set p2d to path to desktop folder as text
else
set p2d to path to documents folder as text
end if
set targetFolder to p2d & targetFolderName & ":"
tell application "System Events"
if not (exists folder targetFolder) then make new folder at end of folder p2d with properties {name:targetFolderName}
end tell -- System Events
(*
(2) Grabs the path to the source spreadsheet
*)
tell application "Pages" to set thePath to path of document dName (* an Unix path *)
tell application "System Events" to set thePath to (path of disk item thePath) as text
(*
(3) Build the name and the path of the temporary Pages document
*)
set tempFolderHFS to path to temporary items
set tempDoc to (tempFolderHFS as text) & dName
tell application "System Events"
if exists disk item tempDoc then delete disk item tempDoc
end tell
tell application "Pages" to tell document dName
set nbSections to count of sections
end tell -- Pages
(*
*************************
* Here we enter the main loop
*************************
*)
repeat with i from 1 to nbSections
set sectionID to i
(*
Grabs datas to build the name of the PDF then
save the document with the temporary sheet in the temporary folder
*)
tell application "System Events" to make new file at end of tempFolderHFS with properties {name:dName}
set fullName to dName & "_section#" & text -5 thru -1 of ("00000" & sectionID)
tell application "Pages"
save document dName in (tempDoc as alias)
end tell -- Pages
(*
Now, the displayed document is the one stored in the temporary items folder.
Builds the name and the pathname of the student's PDF.
*)
if useDateStamp then
set pdfName to fullName & my dateTimeStamp() & ".pdf"
else
set pdfName to fullName & ".pdf"
end if -- useDateStamp
set pdfPath to targetFolder & pdfName
(*
Create the PDF file
*)
tell application "System Events" to make new file at end of folder targetFolder with properties {name:pdfName}
tell application "Pages"
tell document dName
if sectionID < nbSections then
repeat with s from nbSections to (sectionID + 1) by -1
delete section s
end repeat
end if
if sectionID > 1 then
repeat with s from 1 to (sectionID - 1)
delete section s
end repeat
end if
end tell -- temporary document
save document dName as "SLDocumentTypePDF" in (pdfPath as alias)
close document dName without saving
end tell -- Pages
tell application "System Events" to delete disk item tempDoc
tell application "Pages"
open (thePath as alias)
repeat until exists document dName
delay 0.2
end repeat
end tell -- Pages
end repeat -- for next section
end run
--=====
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 dateTimeStamp()
return (do shell script "date +_%Y%m%d-%H%M%S")
end dateTimeStamp
--=====
--[/SCRIPT]
--{code}
Second way to split.
Open the link : http://www.cs.cmu.edu/~benhdj/Mac/unix.html#splitPDF
to grab the Python file Split.py whose name describe what it is designed to achieve : split a PDF file.
Store the downloaded file at the root of your startup volume, say :
Macintosh HD:splitPDF.py
Exec this three lines Applescript (enabler.scpt):
--{code}
set splitter to (path to startup disk as text) & "splitPDF.py"
set splitter to quoted form of POSIX path of splitter
do shell script "chmod a+x " & splitter
--{code}
to get an executable command.
Trigger the terminal man command to get its way of use :
#!/usr/bin/python
“”“Splits an input pdf file into several given a list of split-
ting points (page numbers). “””
author = ‘benhdj@cs.cmu.edu (Benjamin Han)’
import sys import os
from CoreGraphics import *
def Usage ():
print “”" Usage: splitPDF.py inputFN splitPageNum1 splitPa-
geNum2 …
-
inputFN: the path to the input pdf file.
-
splitPageNum1, …: each one is a positive integer; the num-
bers
must not exceed the number of pages of the input file, and
the
entire sequence must be strictly increasing.
Example: splitPDF.py input.pdf 3 5
This will split file input.pdf into 3 files (assuming input.pdf
is 10 pages long):
-
input.part1.1_3.pdf contains page 1-3;
-
input.part2.4_5.pdf contains page 4-5;
-
input.part3.6_10.pdf contains page 6-10.
“”"
if len(sys.argv) < 3:
Usage()
sys.exit(1) else:
inputFN = sys.argv[1]
inputDoc = CGPDFDocumentCreateWithProvider( CGDat-
aProviderCreateWithFilename(inputFN))
if inputDoc:
maxPages = inputDoc.getNumberOfPages()
print ‘%s has %d pages’ % (inputFN, maxPages)
else:
sys.exit(2)
try:
splitPageNums = map(int, sys.argv[2:])
except:
print ‘Error: invalid split page number(s).’
for i, splitPageNum in enumerate(splitPageNums):
if splitPageNum < 1 or splitPageNum > maxPages:
print ‘Error: a split page number must be >= 1 and <= %d.’
% maxPages
sys.exit(3)
elif i and splitPageNums[i - 1] >= splitPageNum:
print ‘Error: split page numbers must be increasing.’
sys.exit(4)
baseFN = os.path.splitext(os.path.basename(inputFN))[0] pageRect
= CGRectMake (0, 0, 612, 792)
if splitPageNums[-1] < maxPages:
splitPageNums.append(maxPages)
Use this other script to split the PDF built thru Export the meted Pages document in a PDF.
--{code}
--[SCRIPT découpe_PDFs.scpt]
--=====
(*
utilisation décrite dans aVosMac n°108
Yvan KOENIG (VALLAURIS, France)
2010/06/12
2010/06/13 - ajouté le déplacement dans le dossier Documents:PDFs_découpés.
2011/08/23 - add ability to define the count of pages of splitted PDFs
*)
--=====
property nom_dossier : "PDFs_découpés"
--=====
(*
Point d'entrée utilisé lorsqu'on double clique l'icône
du script enregistré comme progiciel (application sous 10.6.x).
Si on l'a enregistré en tant que fichier script on peut l'exécuter
dans l'éditeur de scripts ou depuis le menu Scripts.
*)
on run
set un_fichier to choose file of type {"com.adobe.pdf"} without invisibles
my commun(un_fichier)
end run
--=====
(*
Point d'entrée utilisé lorsqu'on glisse & dépose l'icône d'un fichier PDF
sur celle du script enregistré en tant que progiciel (application sous 10.6.x).
*)
on open sel
my commun(item 1 of sel)
end open
--=====
on commun(le_fichier)
local p2startup, dossier_Documents
local dossier_de_stockage, dossier_de_stockage_unix, Date_Heure
local le_script, message_d_erreur, nbPages, _
local ancien_contenu, nouveau_contenu, un_fichier, nom_du_fichier, nouveau_nom
set p2startup to (path to startup disk) as text
(*
Define the count of pages of splitted PDFs to create.
1, 4, 8, 12 are commun values *)
repeat
set pages_per_PDF to text returned of (display dialog "How many pages per splitted PDFs" default answer "8")
try
pages_per_PDF * 1
exit repeat
on error
beep 1
end try
end repeat
set dossier_Documents to (path to documents folder) as text
(*
ATTENTION : ne pas omettre le caractère deux points à la fin de dossier_de_stockage !
*)
set dossier_de_stockage to dossier_Documents & nom_dossier
if dossier_de_stockage does not end with ":" then set dossier_de_stockage to dossier_de_stockage & ":"
set dossier_de_stockage_unix to quoted form of POSIX path of dossier_de_stockage
tell application "System Events"
if not (exists folder dossier_de_stockage) then
make new folder at end of folder dossier_Documents ¬
with properties {name:nom_dossier}
end if
end tell -- System Events
set Date_Heure to do shell script "date +_%Y%m%d-%H%M%S_"
if type identifier of (info for le_fichier) is "com.adobe.pdf" then
set le_script to "/splitPDF.py " & quoted form of POSIX path of le_fichier & space
try
(*
requête incongrue vouée à l'échec
*)
do shell script le_script & "0 0"
on error message_d_erreur
(*
Récupère la liste des fichiers existants à la racine du disque de démarrage
*)
tell application "System Events"
set ancien_contenu to path of every file of folder p2startup
end tell
set nbPages to last word of message_d_erreur
set _ to {}
repeat with i from pages_per_PDF to nbPages by pages_per_PDF
copy i to end of _
end repeat
my recolle(_, space)
(*
On peut enfin appeler correctement le script Python !
*)
do shell script le_script & result
(*
Récupère la liste des fichiers existant maintenant à la racine du disque de démarrage
*)
tell application "System Events"
set nouveau_contenu to path of every file of folder p2startup
end tell
repeat with un_fichier in nouveau_contenu
if (un_fichier is not in ancien_contenu) and ¬
type identifier of (info for file un_fichier) is "com.adobe.pdf" then
(*
C'est un fichier PDF nouvellement créé, il faut le déplacer.
Préfèrant ne pas utiliser le Finder en raison de sa lenteur exaspérante,
il faut gérer la présence éventuelle d'un fichier homonyme dans le dossier destination.
Dans ce cas une chaine date_heure est placée au début du nom de fichier.
Ainsi il n'y aura pas de doublon et les fichiers d'une même opération seront contigus.
*)
tell application "System Events"
set nom_du_fichier to name of file un_fichier
if exists file (dossier_de_stockage & nom_du_fichier) then
set nouveau_nom to Date_Heure & nom_du_fichier
set name of file un_fichier to nouveau_nom
set un_fichier to p2startup & nouveau_nom
end if -- exists file.
end tell -- System Events
do shell script "mv -n " & quoted form of POSIX path of un_fichier & ¬
space & dossier_de_stockage_unix
end if -- (un_fichier is not.
end repeat -- with un_fichier.
end try
end if -- type identifier of (info for.
end commun
--=====
on recolle(l, d)
local oTIDs, l
set oTIDs to AppleScript's text item delimiters
set AppleScript's text item delimiters to d
set t to l as text
set AppleScript's text item delimiters to oTIDs
return t
end recolle
--=====
--[/SCRIPT]
--{code}
You may play with these codes.
Now, I will
(1) try to retrieve the script creating the mails
(2) drive the Merge feature.
CAUTION : I wrote these codes when I used Snow Leopard. I never ran them under Lion.
Yvan KOENIG (VALLAURIS, France) vendredi 2 janvier 2011 10:59:17