PDFkit Selection Bounds

Hello, I’m very new to ASObjC and I’m playing with PDFkit trying to learn. Is there any way to get the bounds (aka NSRect) from a selection?

use framework "Foundation"
use framework "PDFKit"

set NSURL to a reference to NSURL of current application
set PDFDocument to a reference to PDFDocument of current application

set a_url to (NSURL's fileURLWithPath:"/Users/myaccount/Downloads/Test.pdf")
set pdf_doc to (PDFDocument's alloc()'s initWithURL:a_url)

set selectionsArray to pdf_doc's findString:"see" withOptions:1
-- CAN I GET NSRect OF AN ITEM IN selectionsArray?

The array contains PDFSelections. You’ll need to loop through them, getting their pages property – in this case likely to be a single-item array – and then use the boundsForPage: method to get the bounds.

1 Like

I’ve included a suggestion below. My test document was a 1-page PDF consisting of page 14 of Shane’s ASObjC book. I don’t completely understand how Shai1 wants the script to work, but my suggestion does return the bounds of the selection.

use framework "Foundation"
use framework "Quartz"
use scripting additions

-- get a PDF document
set theFile to "/Users/Robert/Working/Test PDF.pdf" -- change to the PDF
set theFile to current application's |NSURL|'s fileURLWithPath:theFile
set theDoc to current application's PDFDocument's alloc()'s initWithURL:theFile
set aPage to (theDoc's pageAtIndex:0)

-- get some info about the PDF FWIW
set totalPages to theDoc's pageCount() as integer --> 1
set pageBounds to aPage's boundsForBox:(current application's kPDFDisplayBoxMediaBox) --> {{0.0, 0.0}, {612.0, 792.0}}

-- information about a selection
set theSelections to theDoc's findString:"puzzle" withOptions:0 -- an array of 1 PDFSelection
# set theSelections to theDoc's findString:"this" withOptions:0 -- an array of 6 PDFSelections FWIW
set firstSelection to theSelections's objectAtIndex:0 --> (PDFSelection) Page count=1, "puzzle"
firstSelection's attributedString() --> (NSConcreteMutableAttributedString) puzzle{NSBaselineOffset = 0; NSColor = "Device CMYK colorspace 0 0 0 1 1"; NSFont = "\"Helvetica 11.00 pt. P [] (0x7ff710db2ce0) fobj=0x7ff70f7e6490, spc=3.06\"";}
set theBounds to firstSelection's boundsForPage:aPage --> {{145.7139, 388.5431}, {28.182, 14.839}}
1 Like

This is EXACTLY what I was looking for. Thanks so much @peavine and @Shane_Stanley! Greatly appreciate the help as I try and learn. From the documentation, I couldn’t understand how to get to this result.