Copying Text From a PDF to a KM Variable?


Is it possible to copy the text inside a .pdf to KM as a variable without even opening the document? let's say that we pass the location of the .pdf as a variable could we then pull out the text into KM and save it as a variable? or at least pull the text out and save to clipboard?


You can use AppleScriptObjC to read the contents of a PDF file and put the contents into a KM variable.

Here is an example that expects the POSIX path of the PDF file to read in KM Var “Path” and returns the contents:

use AppleScript version "2.4" -- Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

use framework "Quartz"

-- classes, constants, and enums used
property NSURL : a reference to current application's NSURL
property PDFDocument : a reference to current application's PDFDocument

tell application "Keyboard Maestro Engine"
	set myPath to getvariable "Path"
end tell

set myDoc to POSIX file myPath
set myPDFDocument to PDFDocument's alloc()'s initWithURL:myDoc

return myPDFDocument's |string|() as text

Hey Ali,

While AppleScriptObjC works well for extracting text from PDFs, it does not do a good job of preserving their layout.

The best tool I've ever found for the job (so far) is pdftotext.

See this topic:

Keyboard Maestro “Convert PDF Files into Text Files in the Front Finder Window” Macro

Don't stop at the first post...


1 Like

This forum is so awesome, I needed to do this today, thanks! Works a treat!