Skip to content

Instantly share code, notes, and snippets.

@jessesquires
Created December 6, 2023 06:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jessesquires/93401538a94fb6b8cdbc56ca673c8e8a to your computer and use it in GitHub Desktop.
Save jessesquires/93401538a94fb6b8cdbc56ca673c8e8a to your computer and use it in GitHub Desktop.
AppleScript to export a Pages document as a PDF
-- Prompt to select the invoice
set theInvoice to choose file with prompt "Please select an invoice:"
-- Get enclosing folder name
tell application "Finder" to set destinationFolder to container of theInvoice
log "Destination folder: " & destinationFolder
tell application "Pages"
activate
open theInvoice
log "Opening: " & theInvoice
try
set documentName to the name of the front document
-- Set new file extension from .pages to .pdf
set newFilename to my findAndReplaceInText(newPagesName, ".pages", ".pdf")
log "New filename: " & newFilename
set the newFilePath to (destinationFolder as string) & newFilename
log "New file path: " & newFilePath
-- Export to pdf
log "Exporting..."
export front document to file newFilePath as PDF
on error errorMessage
display alert "Error: " message errorMessage
end try
log "Closing..."
close every document without saving
end tell
log "Done!"
-- Show exported pdf in Finder
tell application "Finder"
activate
reveal document file newFilePath
log "Renaming original invoice: " & newPagesName
set name of theInvoice to newPagesName
end tell
-- Function to find and replace text in a string
on findAndReplaceInText(theText, theSearchString, theReplacementString)
set AppleScript's text item delimiters to theSearchString
set theTextItems to every text item of theText
set AppleScript's text item delimiters to theReplacementString
set theText to theTextItems as string
set AppleScript's text item delimiters to ""
return theText
end findAndReplaceInText
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment