AppleScript/Automator: renaming PDF with extracted text content of this PDF - pdf

I have a lot of PDFs that I want to rename. The new name should be a text item of this PDF. I wan t to create this as a folder action to drop PDF in and get them renamed. I've com so far with Automator and AppleScript:
The whole text form the PDF is extracted to a new (temporary) file on desktop "PDF2TXT.rtf" (= variable theFileContents), done with the Automator action to extract text from PDF.
Here comes the code that separates the new name out of this text:
on run {theFileContents}
set od to AppleScript's text item delimiters
set theFileContentsText to read theFileContents as text
set myProjectNo to ""
set theDelimiter to "Projectno. "
set oldDelimiters to AppleScript's text item delimiters
set AppleScript's text item delimiters to theDelimiter
set theArray to last text item of theFileContentsText
set theDelimiter to " "
set AppleScript's text item delimiters to theDelimiter
set myProjectNo to first text item of theArray
return myProjectNo
set AppleScript's text item delimiters to oldDelimiters
end run
What I need now is the rest to rename the input PDF to "myProjectNo".
Happy for any suggestion. Thanks in advance.
q3player

try this :
tell application "Finder" to set name of foo to bar
the script to save as droplet (= application) :
on run -- you can run the applet it will prompt for files
open {choose file of type "pdf"}
end run
on open (thesefiles) -- you cn drop files on this applet
repeat with theFileContents in thesefiles
-- set od to AppleScript's text item delimiters -- duplicate : same as oldDelimiters
set theFileContentsText to read theFileContents as text
set oldDelimiters to AppleScript's text item delimiters
set AppleScript's text item delimiters to "Projectno. "
set theArray to last text item of theFileContentsText
set AppleScript's text item delimiters to space
set myProjectNo to first text item of theArray
-- return myProjectNo -- and never come back again ;-)
set AppleScript's text item delimiters to oldDelimiters -- this can't go after the return ( = never called)…
set newPDFname to "Project No" & space & myProjectNo & ".pdf"
tell application "Finder"
display dialog "You really want to renamme this file to " & return & newPDFname & " ?"
set the name of thisFile to newPDFname
end tell
end repeat
end open

Related

Apple Script:Find and replace not working

everybody, I am trying to make the user enter the name of the movie they want subtitles for and the for apple script to automatically search the subtitle website for the name of the movie they inputted.
To do this all of the spaces in the movie name need to be replaced to the + sign because urls convert spaces to the + sign. The code is not working an im getting the following errors:
Expected “end” but found “on”.
A “(” can’t go after this identifier.
Here is my code;
on run
display dialog "What's the name of the movie?" default answer " " with title "What's the name of the movie?" buttons {"OK"} default button 1
set moviename to text returned of the result
set theText to moviename
set theSearchString to " "
set theReplacmentString to "+"
end 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
goToWebPage("https://rs.titlovi.com/prevodi/?prevod= & thetext")
tell application "Safari"
activate
set URL of document 1 to theWebPage
end tell
end goToWebPage
end run
Thank you in advance.
Functions (handlers, in AppleScript speak) may not be nested in AppleScript. So you need to either move findAndReplaceInText and goToWebPage outside of on run, or merge their functionality into on run without using handlers.
Handlers begin with on handlerName and end with end handlerName; you have findAndReplaceInText beginning and ending with end findAndReplaceInText.
Here’s how it might work after separating the handlers:
on run
display dialog "What's the name of the movie?" default answer " " with title "What's the name of the movie?" buttons {"OK"} default button 1
set moviename to text returned of the result
set moviename to findAndReplaceInText(moviename, " ", "+")
goToWebPage("https://rs.titlovi.com/prevodi/?prevod=" & moviename)
end run
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
on goToWebPage(theWebPage)
tell application "Safari"
activate
set URL of document 1 to theWebPage
end tell
end goToWebPage
I’ve verified this code in Safari on Mac OS X 10.14.6.

Create an error text file in Applescript

Here's a script that renames a group of files to their new filenames created in excel. It works and it's great! But the problem is if the files do not exist from the group of files the scripts ends and creates an error..
property sourceFolder : "Macintosh HD:Users:COMP1:Desktop:folder1" -- adjust as appropriate
set filenameList to read file "Macintosh HD:Users:COMP1:Desktop:renamethis.txt" using delimiter {return}
set {oldDelims, text item delimiters} to {text item delimiters, tab}
tell application "Finder"
repeat with aFile in filenameList
set codified_name to (sourceFolder & ":" & (text item 1 of aFile)) as string
set real_name to text item 2 of aFile
set name of file codified_name to real_name
end repeat
end tell
I asked around for some help and they gave me this code to add. The problem is I do not know how and where to add this code and how to define it. I want to be able to create a .txt file that contain the files not renamed instead of stopping the whole script.
try
set name of file codified_name to real_name
on error error_string number error_number
write error_string to log_file_handle starting at eof
end
I don't really know how to code and just rely on posts from the internet and try to tweak them. So if anyone can help me..that would be really really awesome!
Here, this shows how to add a try block into your code above. You needed more code to write to an error log file as well. Should be enough to go on:
property sourceFolder : "Macintosh HD:Users:COMP1:Desktop:folder1" -- adjust as appropriate
set log_file_path to "Macintosh HD:Users:COMP1:Desktop:myErrorLogFile.txt"
set {oldDelims, AppleScript's text item delimiters} to {AppleScript's text item delimiters, tab}
try
set filenameList to read file "Macintosh HD:Users:COMP1:Desktop:renamethis.txt" using delimiter {return}
tell application "Finder"
repeat with aFile in filenameList
set codified_name to (sourceFolder & ":" & (text item 1 of aFile)) as string
set real_name to text item 2 of aFile
set name of file codified_name to real_name
end repeat
end tell
set AppleScript's text item delimiters to oldDelims
on error error_string number error_number
set AppleScript's text item delimiters to oldDelims
set log_file_handle to (open for access file log_file_path with write permission)
write ((current date) as string) & tab & error_string to log_file_handle starting at eof
close access log_file_handle
end try

Issue setting returned text to variable within repeat loop - OS X 10.9.x

The goal of this script is to:
Ask the user how many text replacement (System Preferences>Keyboard>Text) shortcuts they'd like to have. The text returned is set to my variable "gTextReplacementNum" as number. See my second handler "HowMany()"
Have the user provide the text replacement shortcut and the text to do the replacing for the number of shortcuts they wanted. See my third handler "GetText()"
Take the user provided text contained in a variable to create a new AppleScript doc that does all the heavy lifting for them. Code not yet written; not within scope of question.
Then they have a personalized AppleScript Application Bundle they may launch on their Mac to auto-populate the text replacement preferences pane.
I am having trouble getting this to work properly. I need the loop to keep adding the answers to a variable as a list or to a variable that increments its name according to the loop instance (e.g. TextReturned_i, TextReturned_i+1, etc).
Have I adequately explain this?
global gTextReplacementNum
set gTextReplacementNum to 0
# Main Logic Begins
try
Start()
HowMany()
GetText()
on error errText number errNum
display alert "Error " & errNum message errText
end try
# Main Logic Ends
# Handlers Begin
-- First Handler
on Start()
display alert "Automated Text Replacement v1.0" message "Created by: Me
myemail#domain.com" buttons {} giving up after 4
display alert "About" message "This app will have you provide a text 'short cut' to replace with and replacement text. It then compiles all this into an application that can be run on any Mac.
Would you like to continue?" buttons {"No", "Yes"} cancel button 1 default button 2
end Start
-- Second Handler
on HowMany()
display dialog "How many text replacement shortcuts would you like?
Please enter numericals only. (1, 2, 3)" default answer "" buttons {"Cancel", "Okay"} default button 2 cancel button 1
copy the result as list to {ButtonPressed, TextReturned}
set gTextReplacementNum to TextReturned as number
end HowMany
-- Third Handler
on GetText()
repeat with i from 1 to gTextReplacementNum as number
display dialog "What text would you like to replace?
(this is your shortcut)" default answer "" buttons {"Cancel", "Okay"} default button 2 cancel button 1
set TextShortcut to text returned of result as list
display dialog "What is the replacement text?
(this is what the shortcut fills out)" default answer "" buttons {"Cancel", "Okay"} default button 2 cancel button 1
set TextReplaced to text returned of result as list
end repeat
end GetText
# Handlers End
In your GetText() handler, you are replacing the value TextShortcut and TextReplaced each time. You need to
set aList to aList & newValue
to build a list in a repeat loop.
Also, as is, this handler never returns the value of these two lists. So, I'd suggest, using your scheme, make these two variables globals as well.
So, the full changes are:
1. Add to the declarations:
global gTextReplacementNum
global gTextShortcut
global gTextReplaced
set gTextReplacementNum to 0
set gTextShortcut to {}
set gTextReplaced to {}
and 2. edit your GetText() handler:
-- Third Handler
on GetText()
repeat with i from 1 to gTextReplacementNum as number
display dialog "What text would you like to replace?
(this is your shortcut)" default answer "" buttons {"Cancel", "Okay"} default button 2 cancel button 1
set gTextShortcut to gTextShortcut & (text returned of result)
display dialog "What is the replacement text?
(this is what the shortcut fills out)" default answer "" buttons {"Cancel", "Okay"} default button 2 cancel button 1
set gTextReplaced to gTextReplaced & (text returned of result)
end repeat
end GetText
An alternate method would be to read a tab delim file and work from that with a standard script. Something like:
property fileName : "shortcuts.txt"
set filePath to (path to desktop as string) & fileName
set theData to read file filePath
set theRecords to paragraphs of theData
set oldDelim to AppleScript's text item delimiters
set AppleScript's text item delimiters to tab
repeat with thisPair in theRecords
set {theShortcut, theReplacement} to text items of thisPair
setKeyboardPref(theShortcut, theReplacement)
end repeat
set AppleScript's text item delimiters to oldDelim
on setKeyboardPref(theShortcut, theReplacement)
-- set up the pair
display dialog theShortcut & return & theReplacement
end setKeyboardPref

The variable is not defined - Applescript

I made was making this applescript to launch apps with a note:
tell application "Notes"
if exists note starts with applaunch then
set LCommands to {"Launch", "Open"}
repeat with y from 1 to count LCommands
set applaunch to (item y of LCommands)
set AppleScript's text item delimiters to applaunch
set myApp to text items 2 thru 1 of note
set AppleScript's text item delimiters to {""}
set myApp to myApp as text
if y = 1 or y = 2 then
tell application myApp to launch
end if
end repeat
delete note starts with applaunch
end tell
and returns the error "the variable applaunch is not defined" but i defined it. what to do?
You reference applaunch in line 2, but you don't define it until line 5.
Also, your code example is missing the end if that goes with if exists note starts with applaunch then.
You can try something along these lines:
set LCommands to {"Launch ", "Open "}
tell application "Notes"
repeat with aCommand in LCommands
set aCommand to (contents of aCommand)
set myNotes to (notes whose name begins with aCommand)
repeat with aNote in myNotes
set aNote to contents of aNote
set noteName to aNote's name
set AppleScript's text item delimiters to aCommand
set myApp to text items 2 thru -1 of noteName
set AppleScript's text item delimiters to {""}
set myApp to myApp as text
-- If you need to work with the Note's content as plain text
--set noteBody to do shell script "echo " & (quoted form of (aNote's body as text)) & " | textutil -stdin -convert txt -stdout "
my launchDelete(aNote, myApp)
end repeat
end repeat
end tell
on launchDelete(theNote, theApp)
try
tell application theApp to launch
tell application "Notes" to delete theNote
end try
end launchDelete

stringByReplacingOccurrencesOfString: in AppleScript Obj-C

Is there any way I can use the method below or something like this in AppleScript Obj-C?
NSString *request = [urlString stringByReplacingOccurrencesOfString:#"{query}"
withString:queryString];
You can use text item delimiters
set theReplacementString to "-----"
set {theOriginal, text item delimiters} to {text item delimiters, "{query}"}
set theParts to every text item of "{query}asd{query}sadsa{query}"
set text item delimiters to theReplacementString
set theResult to theParts as string
set text item delimiters to theOriginal
return theResult
gives you
"-----asd-----sadsa-----"
This is the code that worked:
set theText to "01 01 2005"
set AppleScript's text item delimiters to " "
set theTextItems to text items of theText
set AppleScript's text item delimiters to "/ "
set theText to theTextItems as string
set AppleScript's text item delimiters to {""}
theText
To answer the first part of your question, you can convert the Cocoa method and use the equivalent ASOC statement (see the AppleScriptObjC Release Notes):
set urlString to current application's NSString's stringWithString_("{query}asd{query}sadsa{query}") -- create an NSString to use with the Cocoa method
set queryString to "-----" -- the replacement string
set request to urlString's stringByReplacingOccurrencesOfString_withString_("{query}", queryString) -- the NSString method in ASOC
display dialog request as text