Skip to content

Instantly share code, notes, and snippets.

@labocho
Created February 10, 2016 07:58
Show Gist options
  • Select an option

  • Save labocho/927f9b910c786b88094d to your computer and use it in GitHub Desktop.

Select an option

Save labocho/927f9b910c786b88094d to your computer and use it in GitHub Desktop.
Open PDF file with Preview.app at specified page
#!/usr/bin/env ruby
# Usage:
# preview path/to/pdf:123 # to open path/to/pdf in Preview.app and jump to specified page
require "open3"
require "json"
OPEN_PAGE_SCRIPT = <<-JS
function run(argv) {
var options = JSON.parse(argv[0]);
var SystemEvents = Application("System Events");
var Preview = Application("Preview");
Preview.activate();
delay(0.01);
SystemEvents.keystroke("g", {using: ["command down", "option down"]});
SystemEvents.keystroke(options.page.toString());
SystemEvents.keyCode(36); // return
}
JS
def sh(*commands)
out, err, status = Open3.capture3(*commands)
unless status.success?
$stderr.puts "command exited with #{status.to_i}"
$stderr.puts err
exit status.to_i
end
out
end
def osascript(source, arg = {})
sh "/usr/bin/osascript", "-l", "JavaScript", "-e", source, arg.to_json
end
def open_page(page)
osascript(OPEN_PAGE_SCRIPT, page: page)
end
files = ARGV
if files.empty?
sh "open", "-a", "Preview"
exit
end
files.each do |file|
if file =~ /(.+):(\d+)\z/
file, page = $1, $2.to_i
end
sh "open", "-a", "Preview", file
if page
open_page(page)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment