use
AppleScript
version "2.4"
-- Yosemite (10.10) or later
use
framework "Foundation"
use
framework "Quartz"
-- for PDF stuff
set
thePath to
POSIX path of (choose file
of type {"pdf"})
set {theRegex,
theError}
to current application's
NSRegularExpression's
regularExpressionWithPattern:"\\d+"
options:0
|error|:(reference)
set
anNSURL
to current application's
|NSURL|'s
fileURLWithPath:thePath
set
oldName
to anNSURL's
lastPathComponent()'s
stringByDeletingPathExtension()
set
newName
to oldName's
stringByAppendingString:"-2.pdf"
set
destURL
to anNSURL's
URLByDeletingLastPathComponent()'s
URLByAppendingPathComponent:newName
-- open doc and count pages
set
theDoc
to current application's
PDFDocument's
alloc()'s
initWithURL:anNSURL
set
theCount
to theDoc's
pageCount()
as integer
-- create list to hold results
repeat
with i from 1 to
theCount
set
thePage to (theDoc's
pageAtIndex:(i - 1))
set
theText
to thePage's
|string|()
set
theRanges
to (theRegex's
matchesInString:theText
options:0
range:{0,
theText's
|length|()})
-- create list to hold contents of matches
-- loop through matches found
repeat
with aFind in
theRanges
-- get the range and start and finish indexes
set
foundRange
to aFind's
range()
set
end of pageFinds
to (theText's
substringWithRange:foundRange)
as text
-- get bounds of the matched text
set
theSelection
to (thePage's
selectionForRange:foundRange)
set
theBounds
to (theSelection's
boundsForPage:thePage)
-- make highlight annotation
set
theHighlight
to (current application's
PDFAnnotationMarkup's
alloc()'s
initWithBounds:theBounds)
(theHighlight's
setMarkupType:(current application's
kPDFMarkupTypeHighlight))
(thePage's
addAnnotation:theHighlight)
set
end of findInfo
to {pageNumber:i,
foundStrings:pageFinds}
theDoc's
writeToURL:destURL