Getting text of PDF w/ ASObjC?

I have the following code that extracts the text from a PDF file, using an automator action save to the desktop:

set workflowpath to (path to desktop folder as text) & "ExtractPDFtext.workflow" -- From https://discussions.apple.com/thread/6847664
set thePDFfile to (choose file of type {"PDF"} default location (path to desktop folder))

set theCommand to "/usr/bin/automator -i " & (quoted form of (POSIX path of thePDFfile)) & " " & (quoted form of (POSIX path of workflowpath))
set output to do shell script theCommand

set outputTextFile to (path to desktop folder as text) & "Extract Text Output.txt"
set theText to (read file outputTextFile)

How would I use ASObjC to do the same, without the automator .workflow file dependency? Bonus points if it doesn’t need to save an interim txt file, just to be read back into the script again. I can run circles around Applescript, but am at a total loss when it comes to ASObjC.

Shane’s ASObjC book contains a script that does what you want. I modified the script to include an option to return text from a particular page if that’s desired. This script assumes that the PDF contains selectable text–it will not do OCR.

use AppleScript version "2.4"
use framework "Foundation"
use framework "Quartz"
use scripting additions

set thePDF to POSIX path of (choose file of type {"pdf"})
set pageNumber to 0 -- set to 0 to get all pages
set theText to getTextFromPDF(thePDF, pageNumber)

on getTextFromPDF(posixPath, pageNumber)
	set theURL to current application's |NSURL|'s fileURLWithPath:posixPath
	set thePDF to current application's PDFDocument's alloc()'s initWithURL:theURL
	if pageNumber = 0 then
		return (thePDF's |string|()) as text
	else
		return ((thePDF's pageAtIndex:(pageNumber - 1))'s |string|()) as text
	end if
end getTextFromPDF
2 Likes

Thanks! That is exactly what I was looking for!