I am currently trying to export an iWork .pages file to a Microsoft Word .docx file with a simple applescript script.
on run {path, fileName}
tell application "Pages"
set theDoc to open (path & "/" & fileName)
set theDocName to name of theDoc
export theDoc as Microsoft Word to file ((path & "/" & theDocName & ".docx") as text)
close theDoc
end tell
end run
I am expecting the document to be exported as a Microsoft Word document however I am receiving the following error:
Pages got an error: The document “1” could not be exported as “/Users/joshgrimmett/Desktop/pages2docs/in/1”. (6)
I managed to export a Pages document to Word with the following script:
on run(_dirname, _filename)
tell application "Pages"
set theDoc to open (_dirname & _filename)
set theDocName to name of theDoc
set dst to (_dirname & theDocName & ".docx")
export theDoc to POSIX file dst as Microsoft Word
close theDoc
end tell
end run
Call the script with e.g. /Users/joshgrimmett/Desktop/pages2docs/in/ and foo.pages (or any other Pages-support extension) as arguments.
I believe the problem was the usage of path (it is a reserved keyword in AS) as a variable, and not specifying the destination class (Since we’re working with POSIX paths and not aliases, it’s POSIX file).
Related
first I am a beginner AppleScript developer. and I have searched this question for a long time but no result found. I have an AppleScript to convert ppt files into pdf format. but the script will hangup after it matches a bad ppt file.
the script/keynote will popup a dialog showing "xxx.ppt can't be opened right now" "the file format is invalid".
is there any way to prevent keynote from popping up this kinds of dialog?
below is the sample code, and file is a image file but I changed extension to pptx to simulate an illegle file:
set thefile to POSIX file "/Users/dazhangluo/Downloads/brain-storming.pptx"
tell application "Keynote"
activate
try
set thedoc to open thefile
--display dialog class of thedoc
on error errMessage
--display dialog errMessage
log errorMessage
end try
end tell
There is a command-line tool called exiftool which can inspect files and get their metadata, including the 'file type' tag (using -filetype). There are a variety of ways to install it†. Unlike 'mdls', it isn't easily fooled by the file extension. If you run it on a pptx file, it will include this in its results:
File Type : PPTX
You can then grab the last word to test. This script will loop through the files in the specified folder, use exiftool to extract their file type, and then copy the alias of any matching file to a new list. It then opens each file in keynote. My version of keynote (v8) doesn't let me script anything with powerpoint documents, so you're on your own at that point.
set srcFol to (path to desktop as text) & "presentations" as alias
-- or if you prefer…
-- set srcFol to choose folder
tell application "Finder"
set fList to files of srcFol as alias list
set cleanList to {}
repeat with f in fList
set ppFile to POSIX path of f
set qfFile to quoted form of ppFile
tell me to set exifData to do shell script "/usr/local/bin/exiftool -filetype " & qfFile
if last word of exifData is "PPTX" then
set end of cleanList to contents of f
--> alias "Mac:Users:username:Desktop:presentations:powerpoint1.pptx"
end if
end repeat
end tell
tell application "Keynote"
activate
repeat with pptxFile in cleanList
open pptxFile
-- do whatever
end repeat
end tell
NB † Depending upon where exiftool is installed, you may need to change the path, which you can get with which exiftool.
I was looking for a script that would batch convert all *.numbers files in a given folder to *.csv files.
I found the following on GitHub and added an additional line as suggested in the comments suggestion. When I run the script, Numbers launches and opens the test file from the folder specified - but the file is not exported. Numbers just stays open and terminal errors out with:
/Users/Shared/Untitled.scpt: execution error: Numbers got an error: Invalid key form. (-10002)
The script (located in /Users/Shared) has the following permissions:
-rwxr-xr-x
#!/usr/bin/osascript
on run argv
set theFilePath to POSIX file (item 1 of argv)
set theFolder to theFilePath as alias
tell application "Finder" to set theDocs to theFolder's items
-- Avoid export privilege problem
set privilegeFile to (theFolder as text) & ".permission"
close access (open for access privilegeFile)
repeat with aDoc in theDocs
set docName to aDoc's name as text
if docName ends with ".numbers" then
set exportName to (theFolder as text) & docName
set exportName to exportName's text 1 thru -9
set exportName to (exportName & "csv")
tell application "Numbers"
open aDoc
delay 5 -- may need to adjust this higher
tell front document
export to file exportName as CSV
close
end tell
end tell
end if
end repeat
end run
Any suggestions?
Here is what I did and works for me in macOS High Sierra:
In Terminal:
touch numb2csv; open -e numb2csv; chmod +x numb2csv
• This creates an empty ASCII Text file named numb2csv.
• Opens, by default, numb2csv in TextEdit.
• Makes the numb2csv file executable.
Copy and paste the example AppleScript code, shown further below, into the opened numb2csv file.
Save and close the numb2csv file.
In Terminal executed the numb2csv executable file, e.g.:
./numb2csv "$HOME/Documents"
This created a CSV file of the same name as each Numbers document in my Documents folder, not traversing any nested folders.
Example AppleScript code:
#!/usr/bin/osascript
on run argv
set theFilePath to POSIX file (item 1 of argv)
set theFolder to theFilePath as alias
tell application "System Events" to set theDocs to theFolder's items whose name extension = "numbers"
repeat with aDoc in theDocs
set docName to aDoc's name as text
set exportName to (theFolder as text) & docName
set exportName to exportName's text 1 thru -8
set exportName to (exportName & "csv")
tell application "Numbers"
launch
open aDoc
repeat until exists document 1
delay 3
end repeat
tell front document
export to file exportName as CSV
close
end tell
end tell
end repeat
tell application "Numbers" to quit
end run
NOTE: As coded, this will overwrite an existing CSV file of the same name as each Numbers file processed, if they already exist. Additional coding required if wanting to not overwrite existing files
If you receive the Script Error:
Numbers got an error: The document “name” could not be exported as “name”. You don’t have permission.
It is my experience that the Numbers document was not fully opened prior to being exported and that increasing the value of the delay command resolves this issue. This is of course assuming that one actually has write permissions in the folder the target Numbers documents exists.
Or one can introduce an error handler within the tell front document block which, if my theory is right about the target document not being fully loaded before the export, will give additional time, e.g.:
Change:
tell front document
export to file exportName as CSV
close
end tell
To:
tell front document
try
export to file exportName as CSV
close
on error
delay 3
export to file exportName as CSV
close
end try
end tell
Note: The primary example AppleScript code is just that and does not contain any error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. See included example directly above.
I was looking for that, unfortunately, that doesn’t work anymore.
This line
tell application "System Events" to set theDocs to theFolder's items whose name extension = "numbers"
Gets the following error:
execution error: Can’t make file "file.numbers" of application "System Events" into the expected type. (-1700)
macOs Big Sur Versio 11.01
automator version 2.10
Numbers version 10.3.5
Inspired by this thread and those articles Exporting Numbers Documents and Get full directory contents with AppleScript
The following code works:
#!/usr/bin/osascript
log "Start"
property exportFileExtension : "csv"
tell application "Finder"
activate
set sourceFolder to choose folder with prompt "Please select directory."
set fileList to name of every file of sourceFolder
end tell
set the defaultDestinationFolder to sourceFolder
repeat with documentName in fileList
log "documentName: " & documentName
set fullPath to (sourceFolder as text) & documentName
log "fullPath: " & fullPath
if documentName ends with ".numbers" then
set documentName to text 1 thru -9 of documentName
tell application "Finder"
set newExportItemName to documentName & "." & exportFileExtension
set incrementIndex to 1
repeat until not (exists document file newExportItemName of defaultDestinationFolder)
set newExportItemName to ¬
documentName & "-" & (incrementIndex as string) & "." & exportFileExtension
set incrementIndex to incrementIndex + 1
end repeat
end tell
set the targetFileHFSPath to ¬
(defaultDestinationFolder as string) & newExportItemName
tell application "Numbers"
launch
open fullPath
with timeout of 1200 seconds
export front document to file targetFileHFSPath as CSV
end timeout
close
end tell
end if
end repeat
user3439894's answer works with a few change:
exists document 1 => number of documents > 0
I have an Applescript to convert a XLSX to XLS. I can get the file from a Google Team Drive (via Drive File Stream), convert and save it to my desktop. When I try to save it to a "Out" folder on a Google Team Drive I get a error.
I believe my output path isn't correct. I've tried different ways to reach the path, with no luck.
Working code saving to Desktop:
set {year:y, month:m, day:d, time:t} to (current date)
set today to (m as number) & d & y
set TSCfilein to "Volumes:GoogleDrive:Team Drives:Sales:Customer Service:Inventory Feeds:TSC:In:TSC_Master.xlsx"
set TSCfileout to (path to desktop as text) & "TSC" & today & ".xls" as string
tell application "Microsoft Excel"
activate
open file TSCfilein
tell workbook 1
tell sheet 1
save active workbook in TSCfileout as Excel98to2004 file format
end tell
close without saving
end tell
end tell
Changing set TSCfileout to the following causes the error:
set TSCfileout to "Volumes:Google Drive:Team Drives:Sales:Customer Service:Inventory Feeds:TSC:Out" & "TSC" & today & ".xls" as string
The expected result is to save the file Google Team Drive folder.
Error:
"Microsoft Excel got an error: active workbook of sheet 1 of workbook 1 doesn’t understand the “save” message." when I try to point the output file location.
There is a general misunderstanding: HFS paths start always with a disk name, but never with Volumes.
Don't mix it up with POSIX paths.
The startup volume "Macintosh HD" as POSIX path is / as HFS path Macintosh HD
The external volume "Google Drive" as POSIX path is /Volumes/Google Drive as HFS path Google Drive
And there is a missing colon after Out
Your path to the external volume is
set TSCfileout to "Google Drive:Team Drives:Sales:Customer Service:Inventory Feeds:TSC:Out:" & "TSC" & today & ".xls"
The trailing coercion as string is redundant. According to the rules the leftmost type is the result type of a concatenation.
I'm trying to get a script working which is able to batch export .mts format video files via quicktime into .mov files in 1080p. The script fails with the following error: "The action “Run AppleScript” encountered an error: “QuickTime Player got an error: Can’t make file (document "00000.MTS") into type «class fsrf».”". I assume this has something to do with using text file paths? Note I'm not experienced with Applescript and would really appreciate any help to get this simple bit of script working. Currently it's in automator as a service:
on run {inputFiles}
if inputFiles is equal to {} then
set inputFiles to (choose file with prompt "Select the file(s) to convert:" with multiple selections allowed without invisibles)
end if
open inputFiles
end run
on open droppedItems
tell application "Finder" to set inputFolder to (container of first item of droppedItems) as Unicode text
set outputFolder to (choose folder with prompt "Select output folder:" default location (inputFolder as alias)) as Unicode text
set exportPreset to (choose from list {"Movie", "iPhone", "iPod", "480p", "720p", "1080p"} with prompt "Choose QuickTime Export Preset:") as Unicode text
if exportPreset is equal to "false" then
return
end if
repeat with currentItem in droppedItems
repeat until getProcessPercentCPU("CoreMediaAuthoringSessionHelper") is equal to ""
end repeat
tell application "Finder" to set fileName to name of currentItem as Unicode text
set fileName to text 1 thru ((fileName's length) - (offset of "." in ¬
(the reverse of every character of fileName) as text)) of fileName
convertFile(currentItem, outputFolder & fileName & ".mov", exportPreset)
end repeat
end open
on convertFile(inputFile, outputFile, exportPreset)
tell application "QuickTime Player"
set thisMovie to open inputFile
open for access file thisMovie
close access file thisMovie
export thisMovie in (outputFile) using settings preset exportPreset
close thisMovie
end tell
end convertFile
on getProcessPercentCPU(processName)
do shell script "/bin/ps -xco %cpu,command | /usr/bin/awk '/" & processName & "$/ {print $1}'"
end getProcessPercentCPU
Try changing:
set outputFolder to (choose folder with prompt "Select output folder:" default location (inputFolder as alias)) as Unicode text
to:
set outputFolder to POSIX path of (choose folder with prompt "Select output folder:" default location (inputFolder as alias))
and:
convertFile(currentItem, outputFolder & fileName & ".mov", exportPreset)
to:
set outputFile to POSIX file (outputFolder & fileName & ".mov")
convertFile(currentItem, outputFile, exportPreset)
and remove the open for access/close access commands.
Sandboxed apps don't like receiving path strings to open/save commands, but accept alias/POSIX file values okay. (If it still doesn't work then it's some other issue at play, but that's always the first thing to check when you get a filesystem permissions error as you describe.)
The error occurs because thisMovie is a document reference of QuickTime Player and this class cannot be converted / coerced to a file system reference («class fsrf»).
That's what the error message says
Can’t make file (document "00000.MTS") into type «class fsrf»
The Standard Additions command open for access does not support QuickTime Player documents anyway. What is the purpose of the open / close lines?
Note:
as Unicode text as coercion to string is outdated since macOS 10.5 Leopard. It's only used with read and write commands to handle UTF16 encoded text. A coercion to standard AppleScript text is simply written as text. In case of name of currentItem it's redundant anyway because the class of name is always text.
I am at my wit's end. I have tried all variations to get this script to work. The error I get is Adobe Photoshop CS6 got an error: Can’t get current document. and the highlighted script error is my "export in file newFileName.." block. I've tried putting alias in different positions, using file, not using file. Also I get this error message, but the actual script seems to stop working right after "set docName to name of docRef"
And basically I just copied this code from another script that was working fine and just changed a save this file... to a export this file...
-- set the folders that you want to use
set inputFolder to choose folder with prompt "Choose the folder of images to downsize."
set pathToDesktop to (path to desktop folder as string)
set outputFolder to pathToDesktop & "PhotoshopRetina:"
tell application "Finder"
set filesList to files in folder inputFolder
if not (exists folder outputFolder) then
make new folder at desktop with properties {name:"PhotoshopRetina"}
end if
end tell
with timeout of 86400 seconds
tell application "Adobe Photoshop CS6"
set display dialogs to never
close every document saving no
end tell
repeat with aFile in filesList
tell application "Finder"
-- The step below is important because the 'aFile' reference as returned by
-- Finder associates the file with Finder and not Photoshop. By converting
-- the reference below 'as alias', the reference used by 'open' will be
-- correctly handled by Photoshop rather than Finder.
set theFile to aFile as string
set theFileName to name of aFile
set theFileInfo to info for alias theFile
if kind of theFileInfo is "Adobe Photoshop JPEG file" then
my retinaDisplay(theFile)
end if
end tell
end repeat
end timeout
end
on retinaDisplay(theFile)
tell application "Adobe Photoshop CS6"
open alias theFile
set docRef to the current document
-- Convert the document to a document mode that supports saving as jpeg
if (mode of docRef is not RGB) then
change mode docRef to RGB
end if
tell docRef
set color profile kind to none
end tell
set infoRef to get info of docRef
set docName to name of docRef
set docBaseName to getBaseName(docName) of me
set newFileName to (my outputFolder as string) & docBaseName & ".jpg"
tell current document
export in file newFileName as save for web with options {class:save for web export options, web format:JPEG, embed color profile:false, quality:45} with copying
end tell
close current document without saving
end tell
end retinaDisplay
-- Returns the document name without extension (if present)
on getBaseName(fName)
set baseName to fName
repeat with idx from 1 to (length of fName)
if (item idx of fName = ".") then
set baseName to (items 1 thru (idx - 1) of fName) as string
exit repeat
end if
end repeat
return baseName
end getBaseName
end
If I open an image in photoshop I can run this code with no errors.
set f to (path to desktop as text) & "test.jpg"
tell application "Adobe Photoshop CS6"
tell current document
export in file f as save for web
end tell
end tell
However, if I additionally add your "with options" code then I get your error. I don't even know what the "with copying" part is. I don't think that means anything to photoshop. So the problem is not with the "current document". The problem is with your options. You must be doing that part wrong.
Good luck.