Renaming PDF File with Apple Script - applescript

I'm trying to rename a finder item called "Invoice Template.pdf" when it is added to my folder with Automator. However, every time the script runs, I get Finder got an error: Can’t set file "Invoice Template.pdf" to "Invoice 11.08.2021.pdf". Any ideas why?
tell application "Finder"
set dateObj to (current date)
set theMonth to text -1 thru -2 of ("0" & (month of dateObj as number))
set theDay to text -1 thru -2 of ("0" & day of dateObj)
set theYear to year of dateObj
set dateStamp to "" & theMonth & "." & theDay & "." & theYear
set theFile to "DBF Invoice Template.pdf"
set theName to "Invoice"
set the name of file theFile to theName & " " & dateStamp & ".pdf"
end tell

set dateObj to (current date)
set theMonth to text -1 thru -2 of ("0" & (month of dateObj as number))
set theDay to text -1 thru -2 of ("0" & day of dateObj)
set theYear to year of dateObj
set dateStamp to "" & theMonth & "." & theDay & "." & theYear
set theFileHFS to (choose file of type "com.adobe.pdf") as text
set theName to "Invoice"
tell application "Finder"
set the name of file theFileHFS to theName & " " & dateStamp & ".pdf"
end tell

You need to tell Finder where the file is:
property myFolder: "/Users/MYUSERNAME/Dropbox/Invoices" as POSIX file
tell application "Finder"
...
set theFile to "DBF Invoice Template.pdf"
set theName to "Invoice"
set the name of file theFile of folder myFolder to theName & " " & dateStamp & ".pdf"
end tell

Related

Applescript to rename a file in a folder

Still a Noob / novice here
So I am trying to rename a file within a folder
set newfoldername to DT & "-" & JobName & " - " & Wedding --Adds Date, Couples name and event type to make directory name
MORE CODE HERE
set destFolder to loc & newfoldername & ":Final Delivery:DVD:"
tell application "Finder"
duplicate file sourcedvdtemp to folder destFolder
set the name of file "DVD_template.dspproj" to newfoldername
end tell
But I just get an error
"error "Finder got an error: Can’t set file \"DVD_template.dspproj\" to \"newfoldername.dspproj\"." number -10006 from file "DVD_template.dspproj""
I have tried various ways, with and without the extension "newfoldername" is set above and creates a folder with the users input as a name
Am I just being stupid or have I missed something completely.
EDIT
tell application "Finder" to set frontmost to true
set DT to text returned of (display dialog "Please enter the wedding date" default answer "YYYY/MM/DD") --Asks for date of wedding
set JobName to text returned of (display dialog "Please enter the couples name" default answer "Bride & Groom + Surname") --Asks for couples name
set Wedding to text returned of (display dialog "Please enter the type of day" default answer "Wedding") --Asks for type of day, Wedding, Party, etc
--Creates directory with info from above
set loc to (choose folder "Please choose where you would like to save the files") as text --Loc = Location of where directory will be placed
set newfoldername to DT & "-" & JobName & " - " & Wedding --Adds Date, Couples name and event type to make directory name
set folderStructure to "/{Audio/{Music,RAW\\ Audio\\ Cards},Documents,Exports,FCPX\\ Library,Film\\ Poster,Final\\ Delivery/{DVD,USB,WEB},Images/{Graphics,Stills},RAW\\ Cards/{C100-1,C100-2,7D,100D},XML}"
do shell script "mkdir -p " & quoted form of POSIX path of (loc & newfoldername) & folderStructure
set sourcedvdtemp to (path to movies folder as text) & "## - WeddingTemplate - ##:DVD_template.dspproj" --Gets file DVD_template
set sourceusbtemp to (path to movies folder as text) & "## - WeddingTemplate - ##:USB_template.zip" --Gets file USB_template
set sourcewebtemp to (path to movies folder as text) & "## - WeddingTemplate - ##:WEB_template.zip" --Gets file WEB_template
set sourcefcpxtemp to (path to movies folder as text) & "## - WeddingTemplate - ##:FCPX_template.fcpbundle" --Gets file FCPX_template
set sourcefilmpostemp to (path to movies folder as text) & "## - WeddingTemplate - ##:FILM_POSTER_Template.psd" --Gets file FILM_POSTER_template
set destFolder to loc & newfoldername & ":Final Delivery:DVD:"
tell application "Finder"
duplicate file sourcedvdtemp to folder destFolder
set the name of file "DVD_template.dspproj" to newfoldername
end tell
set destFolder to loc & newfoldername & ":FCPX Library:"
tell application "Finder"
duplicate file sourcefcpxtemp to folder destFolder
set the name of file "FCPX_template.fcpbundle" to newfoldername
end tell
set destFolder to loc & newfoldername & ":Film Poster:"
tell application "Finder"
duplicate file sourcefilmpostemp to folder destFolder
set the name of file "FILM_POSTER_Template.psd" to newfoldername
end tell
You are trying to rename a file "DVD_template.dspproj" on desktop which obviously does not exist. The desktop folder is the root folder of the Finder.
The duplicate command of the Finder returns the duplicated file so it's simply
tell application "Finder"
set fileExtension to name extension of file sourcedvdtemp
set duplicatedFile to duplicate file sourcedvdtemp to folder destFolder
set name of duplicatedFile to newfoldername & "." & fileExtension
end tell
If you want to rename the file to newfoldername you have to copy and add the file extension.
PS: Instead of calculating the template folder 5 times I recommend to write
set weddingTemplateFolder to (path to movies folder as text) & "## - WeddingTemplate - ##:"
set sourcedvdtemp to weddingTemplateFolder & "DVD_template.dspproj" --Gets file DVD_template
set sourceusbtemp to weddingTemplateFolder & "USB_template.zip" --Gets file USB_template
... etc.

Extracting Gif Files and putting them in a folder within the contents of the app

The AppleScript I'm making extracts the frames from a gif file and puts the individual images in a folder inside the application's contents. It then changes the desktop background rapidly to the images inside the folder, hence giving you a gif for a wallpaper. However, I can't figure out how to extract the gif files to the folder in the application. This is what I have so far:
on delay duration
set endTime to (current date) + duration
repeat while (current date) is less than endTime
tell AppleScript to delay duration
end repeat
end delay
set gifFiles to choose file of type "com.compuserve.gif" with prompt "Select GIF"
tell application "System Events" to set gifFileName to name of gifFiles
set dest to quoted form of POSIX path of (path to me) & "Contents:Resources:Gif"
set pScript to quoted form of "from AppKit import NSApplication, NSImage, NSImageCurrentFrame, NSGIFFileType; import sys, os
tName=os.path.basename(sys.argv[1])
dir=sys.argv[2]
app=NSApplication.sharedApplication()
img=NSImage.alloc().initWithContentsOfFile_(sys.argv[1])
if img:
gifRep=img.representations()[0]
frames=gifRep.valueForProperty_('NSImageFrameCount')
if frames:
for i in range(frames.intValue()):
gifRep.setProperty_withValue_(NSImageCurrentFrame, i)
gifRep.representationUsingType_properties_(NSGIFFileType, None).writeToFile_atomically_(dir + tName + ' ' + str(i + 1).zfill(2) + '.gif', True)
print (i + 1)"
repeat with f in gifFiles
set numberOfExtractedGIFs to (do shell script "/usr/bin/python -c " & pScript & " " & (quoted form of POSIX path of f) & " " & dest) as integer
end repeat
repeat
try
set desktop_image to (path to me as string) & "Contents:Resources:Gif:" & gifFileName & " 01.gif"
tell application "Finder" to set the desktop picture to desktop_image
end try
delay 0.05
try
set desktop_image to (path to me as string) & "Contents:Resources:Gif:" & gifFileName & " 02.gif"
tell application "Finder" to set the desktop picture to desktop_image
end try
delay 0.05
try
set desktop_image to (path to me as string) & "Contents:Resources:Gif:" & gifFileName & " 03.gif"
tell application "Finder" to set the desktop picture to desktop_image
end try
delay 0.05
try
set desktop_image to (path to me as string) & "Contents:Resources:Gif:" & gifFileName & " 04.gif"
tell application "Finder" to set the desktop picture to desktop_image
end try
delay 0.05
try
set desktop_image to (path to me as string) & "Contents:Resources:Gif:" & gifFileName & " 05.gif"
tell application "Finder" to set the desktop picture to desktop_image
end try
end repeat
There are some issues in the script.
choose file returns a single file. The repeat loop repeat with f in gifFiles breaks the script.
The proper POSIX path to the destination folder is
set dest to quoted form of (POSIX path of (path to me) & "Contents/Resources/Gif")
A slash must be added when composing the file path
Try this, the script assumes that the folder Gif in the Resources folder exists.
set gifFile to choose file of type "com.compuserve.gif" with prompt "Select GIF"
tell application "System Events" to set gifFileName to name of gifFile
set dest to quoted form of (POSIX path of (path to me) & "Contents/Resources/Gif")
set pScript to quoted form of "from AppKit import NSApplication, NSImage, NSImageCurrentFrame, NSGIFFileType; import sys, os
tName=os.path.basename(sys.argv[1])
dir=sys.argv[2]
app=NSApplication.sharedApplication()
img=NSImage.alloc().initWithContentsOfFile_(sys.argv[1])
if img:
gifRep=img.representations()[0]
frames=gifRep.valueForProperty_('NSImageFrameCount')
if frames:
for i in range(frames.intValue()):
gifRep.setProperty_withValue_(NSImageCurrentFrame, i)
gifRep.representationUsingType_properties_(NSGIFFileType, None).writeToFile_atomically_(dir + '/' + tName + ' ' + str(i + 1).zfill(2) + '.gif', True)
print (i + 1)"
do shell script "/usr/bin/python -c " & pScript & " " & (quoted form of POSIX path of gifFile) & " " & dest
tell application "Finder"
set extractedGiFFiles to files of folder ((path to me as text) & "Contents:Resources:Gif:")
repeat
repeat with aFile in extractedGiFFiles
set the desktop picture to aFile
delay 0.05
end repeat
end repeat
end tell

Set creation date using SetFile / date formatting

I'd like to copy creation date from a file and apply it to the folder the file is sitting in. I'm using SetFile for this purpose. I"m getting error: Invalid date/time. My assumption is that it's the format of the date that is not working. How do I format the date properly? Could someone suggest solution? Thanks
set filesToProcess to choose folder with prompt "Select folders:" with multiple selections allowed
repeat with thisFile in filesToProcess
tell application "Finder"
try
set creationDate to creation date of (first file in the entire contents of thisFile whose name ends with "low_r.pdf")
set formattedCreationDate to --creationDate needs reformatting?
do shell script "SetFile -d " & formattedCreationDate & " " & quoted form of (POSIX path of thisFile)
on error fileNotFound
set label index of thisFile to 2
display dialog fileNotFound
end try
end tell
end repeat
Final working code:
set filesToProcess to choose folder with prompt "Select folders:" with multiple selections allowed
repeat with thisFile in filesToProcess
tell application "Finder"
try
set creationDate to creation date of (first file in the entire contents of thisFile whose name ends with "low_r.pdf")
set formattedCreationDate to quoted form of my stringForDate(creationDate)
set formattedFolderLocation to quoted form of (POSIX path of thisFile)
do shell script "SetFile -d " & formattedCreationDate & " " & formattedFolderLocation
on error errorMsg
set label index of thisFile to 2
--display dialog errorMsg
end try
end tell
end repeat
on stringForDate(aDate)
if aDate is "" then return null
if class of aDate is not date then return null
set {year:dYear, month:dMonth, day:dDay, hours:dHours, minutes:dMinutes, seconds:dSeconds} to aDate
set dMonth to dMonth as integer
if dMonth < 10 then set dMonth to "0" & dMonth
if dDay < 10 then set dDay to "0" & dDay
return ((dMonth & "/" & dDay & "/" & dYear & " " & dHours & ":" & dMinutes & ":" & dSeconds) as string)
end stringForDate
Thanks to everyone for contributions and #Zero for sharing the subroutine
Try this.
set filesToProcess to choose folder with prompt "Select folders:" with multiple selections allowed
repeat with thisFile in filesToProcess
tell application "Finder"
try
set theFileDate to (creation date of (first file in folder thisFile whose name ends with "low_r.pdf"))
set formattedCreationDate to (word 2 of short date string of theFileDate & "/" & word 1 of short date string of theFileDate & "/" & word 3 of short date string of theFileDate) & space & time string of theFileDate
--need to flip dd/mm/yyyy to be mm/dd/yyyy Ues this line -->>set formattedCreationDate to short date string of theFileDate & space & time string of theFileDate <<-- instead if your country's date format is already mm/dd/yyyy
my doCommand(formattedCreationDate, thisFile)
on error fileNotFound
set label index of thisFile to 2
display dialog fileNotFound
end try
end tell
end repeat
on doCommand(formattedCreationDate, thisFile)
do shell script "SetFile -d " & (quoted form of formattedCreationDate) & " " & quoted form of (POSIX path of thisFile)
end doCommand

applescript code for showing image property

I am new to applescript. I want to develop an application in applescript.
Below is my code. And while running it, it's showing finder that can't make alias. Kindly help me.
property script_name : "image Tracker"
property script_description : "image property data finder"
--set the_folder to (choose folder with prompt "Select the folder for get the image property:") as Unicode text
--set the_folder to quoted form of POSIX path of (choose folder with prompt "Select the folder for get the image property:")
set the_folder to (choose folder)
copy {"jpg", "png", "eps", "ai", "tif", "psd", "gif"} to validExtentions
tell application "Finder" to set fPaths to file the_folder
repeat with thisFilePath in fPaths
if name extension of thisFilePath is in validExtensions then
try
tell application "Image Events"
-- start the Image Events application
launch
-- open the image file
set this_image to open this_file
-- extract the properties record
set the props_rec to the properties of this_image
-- purge the open image data
close this_image
-- extract the property values from the record
set the image_info to ""
set the image_info to the image_info & ¬
"Name: " & (name of props_rec) & return
set the image_info to the image_info & ¬
"*********************************************" & return
set the image_info to the image_info & ¬
"File: " & (path of image file of props_rec) & return
set the image_info to the image_info & ¬
"File Type: " & (file type of props_rec) & return
set the image_info to the image_info & ¬
"Res: " & item 1 of (resolution of props_rec) & return
set the image_info to the image_info & ¬
"Color Space: " & (color space of props_rec) & return
copy (dimensions of props_rec) to {x, y}
set the image_info to the image_info & ¬
"Dimemsions: " & x & ", " & y
end tell
on error error_message
display dialog error_message
end try
end if
end repeat
set myfile to open for access ("Macintosh HD:Users:varghese.pt:Desktop:") & "image_data.txt" with write permission
write image_info to myfile
close access myfile
If anyone found the answer, please send me the details.
Thanks in advance.
Nidhin Joseph
Let me say up front: Unfortunately, in general, AppleScript is a finicky beast, and sometimes trial and error are your only friends.
There are several problems with your code - some obvious, one not:
validExtentions is misspelled in the copy {"jpg ... statement - you later refer to with the (correctly spelled) name validExtensions
In the tell application "Finder" command, you must replace file with folder.
In command set this_image to open this_file, you must replace this_file with (thisFilePath as text). NOTE: Parenthesizing and as text is crucial, as the file will otherwise be opened by Finder (and therefore open in Preview.app) - don't ask me WHY this is so.
I also suggest replacing the hard-coded path in the write-to-file command with (path to desktop as text) & "image_data.txt"
If we put it all together, we get:
copy {"jpg", "png", "eps", "ai", "tif", "psd", "gif"} to validExtensions
set the_folder to (choose folder)
tell application "Finder" to repeat with thisFilePath in folder the_folder
if name extension of thisFilePath is in validExtensions then
try
tell application "Image Events"
# start the Image Events application
launch
# open the image file
# set this_image to open thisFilePath
set this_image to open (thisFilePath as text)
# extract the properties record
set the props_rec to the properties of this_image
# purge the open image data
close this_image
# extract the property values from the record
set the image_info to ""
set the image_info to the image_info & ¬
"Name: " & (name of props_rec) & return
set the image_info to the image_info & ¬
"*********************************************" & return
set the image_info to the image_info & ¬
"File: " & (path of image file of props_rec) & return
set the image_info to the image_info & ¬
"File Type: " & (file type of props_rec) & return
set the image_info to the image_info & ¬
"Res: " & item 1 of (resolution of props_rec) & return
set the image_info to the image_info & ¬
"Color Space: " & (color space of props_rec) & return
copy (dimensions of props_rec) to {x, y}
set the image_info to the image_info & ¬
"Dimensions: " & x & ", " & y
# my dlog(image_info)
end tell
on error error_message
display dialog error_message
end try
end if
end repeat
set myfile to open for access (path to desktop as text) & "image_data.txt" with write permission
write image_info to myfile
close access myfile
Finally, you can improve the performance of your code by switching from enumerating files in the Finder context to enumerating in the System Events context:
If you substitute the following two lines for their current counterparts in the code above, your script will run much more quickly. Why, you ask? Again, I do not know.
tell application "System Events" to repeat with thisFilePath in alias (the_folder as text)
set this_image to open (get path of thisFilePath)

Applescript: Passing track metadata from text file to broadcast streaming app

I know virtually nothing about AppleScript and could do with some help.
While running, my broadcast playout system (MegaSeg) writes details of the track currently playing to a textfile called "NowPlaying" which contains solely the following contents, each on its own line and without square brackets:
Title: [title]
Artist: [artist]
Album: [album]
Time: [time in some format or other]
I want to pass this to my broadcast streamer LadioCast, which can be addressed via AppleScript, so that it sends info on what is playing to the streaming server.
MegaSeg doesn't support Applescript calls like 'tell application "MegaSeg"... set trackName to name of current track' so I can't do it that way. I have no idea about how to do this.
If we imagine that I was able to grab that info, this is what I would do with it:
set lastName to ""
set lastArtist to ""
set lastAlbum to ""
repeat
** insert missing file reading section here
** in the following, "title", "artist" and "album" are from the text file **
set trackName to title
set trackArtist to artist
set trackAlbum to album
** end of missing section
if trackName is not lastName and trackArtist is not lastArtist and trackAlbum is not lastAlbum then
set lastName to trackName
set lastArtist to trackArtist
set lastAlbum to trackAlbum
tell application "LadioCast"
set metadata song to trackName & " – " & trackArtist & " – " & trackAlbum
end tell
end if
delay 15
end repeat
Thanks in advance.
--Richard E
===
I tried the suggestions from #DigiMonk and they were very helpful, but not all of them worked. First, the file is in a specific location and not on the desktop; second, I could not get 'trim_line' to work at all - I got "script does not understand trim_line message". However the text in the file seems to be already trimmed.
The script below nearly works; when run from the Applescript Editor it does seem to get the Title, Artist and Album into the variables. However when I try running it from LadioCast I get an EOF -39 error. More importantly, as soon as I run this, MegaSeg stops updating the file, forever. I am presumably locking the file to read from it and stopping MegaSeg writing to it. How do I avoid this?
set lastName to ""
set lastArtist to ""
set lastAlbum to ""
set lastTime to ""
set trackName to ""
set trackArtist to ""
set trackAlbum to ""
set sourcePath to ""
repeat
set sourcePath to open for access file "Library:MegaSeg User Data:Logs:Logs for MegaSeg System (4):NowPlaying"
set thisText to read sourcePath as text
close access file "Library:MegaSeg User Data:Logs:Logs for MegaSeg System (4):NowPlaying"
set the paragraphList to every paragraph of thisText
repeat with i from 1 to number of items in paragraphList
set thisItem to item i of paragraphList
if thisItem starts with "Title:" then
set x to the offset of "Title:" in thisItem
set trackName to (text (x + 6) thru -1 of thisItem)
else if thisItem starts with "Artist:" then
set x to the offset of "Artist:" in thisItem
set trackArtist to (text (x + 7) thru -1 of thisItem)
else if thisItem starts with "Album:" then
set x to the offset of "Album:" in thisItem
set trackAlbum to (text (x + 6) thru -1 of thisItem)
end if
end repeat
if trackName is not lastName and trackArtist is not lastArtist and trackAlbum is not lastAlbum then
set lastName to trackName
set lastArtist to trackArtist
set lastAlbum to trackAlbum
tell application "LadioCast"
set metadata song to trackName & " – " & trackArtist & " – " & trackAlbum
end tell
end if
delay 15
end repeat
May be this helps: (feed sourcePath with the path to your NowPlaying.txt file)
set sourcePath to (path to desktop) & "NowPlaying.txt" as text
set thisText to my readFile(sourcePath)
set the paragraphList to every paragraph of thisText
set lastName to ""
set lastArtist to ""
set lastAlbum to ""
set lastTime to ""
repeat with i from 1 to number of items in paragraphList
set thisItem to item i of paragraphList
--log thisItem
if thisItem starts with "Title:" then
set x to the offset of "Title:" in thisItem
set y to (text (x + 6) thru -1 of thisItem)
set lastName to my trim_line(y, " ", 2)
else if thisItem starts with "Artist:" then
set x to the offset of "Artist:" in thisItem
set y to (text (x + 7) thru -1 of thisItem)
set lastArtist to my trim_line(y, " ", 2)
else if thisItem starts with "Album:" then
set x to the offset of "Album:" in thisItem
set y to (text (x + 6) thru -1 of thisItem)
set lastAlbum to my trim_line(y, " ", 2)
else if thisItem starts with "Time:" then
set x to the offset of "Time:" in thisItem
set y to (text (x + 5) thru -1 of thisItem)
set lastTime to my trim_line(y, " ", 2)
end if
end repeat
log "lastName = '" & lastName & "'"
log "lastArtist = '" & lastArtist & "'"
log "lastAlbum = '" & lastAlbum & "'"
on readFile(thisFile)
set thisFile to thisFile as text
if thisFile is "" then return ""
try
set fi to open for access file the thisFile
set myData to read fi as text
close access file the thisFile
return myData
on error
try
close access file the thisFile
return ""
end try
end try
end readFile
on trim_line(this_text, trim_chars, trim_indicator)
-- 0 = beginning, 1 = end, 2 = both
set x to the length of the trim_chars
-- TRIM BEGINNING
if the trim_indicator is in {0, 2} then
repeat while this_text begins with the trim_chars
try
set this_text to characters (x + 1) thru -1 of this_text as string
on error
-- the text contains nothing but the trim characters
return ""
end try
end repeat
end if
-- TRIM ENDING
if the trim_indicator is in {1, 2} then
repeat while this_text ends with the trim_chars
try
set this_text to characters 1 thru -(x + 1) of this_text as string
on error
-- the text contains nothing but the trim characters
return ""
end try
end repeat
end if
return this_text
end trim_line

Resources