Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to open PDFs with Preview.app at a certain page?

Tags:

macos

cocoa

I can happily open a PDF file at path with Preview.app from within my application using

[NSWorkspace.sharedWorkspace openFile: path];

However, I would like to launch Preview.app with that file at a certain page. Is this possible, e.g. by passing a specific NSAppleEventDescriptor in NSWorkspace's

- (BOOL)openURLs:(NSArray *)urls withAppBundleIdentifier:(NSString *)bundleIdentifier options:(NSWorkspaceLaunchOptions)options additionalEventParamDescriptor:(NSAppleEventDescriptor *)descriptor launchIdentifiers:(NSArray **)identifiers

method? QuickLook can do this and I would like to imitate this behavior.

Thanks for any help!

like image 528
goetz Avatar asked Oct 22 '22 21:10

goetz


1 Answers

You can do this via NSAppleScript.

Here's an NSWorkspace category method that opens the file and jumps to the specified page:

- (void)openPreviewFile:(NSString*)filePath onPage:(int)pageNumber {
    [self openFile:filePath];

    NSString *sysEvents = @"System Events";

    NSString *source = [NSString stringWithFormat:@"tell application \"%@\" to activate\ntell application \"%@\" to keystroke \"g\" using {command down, option down}\ndelay %f\ntell application \"%@\" to keystroke \"%i\"\ntell application \"%@\" to keystroke return",
                        @"Preview", sysEvents, 0.5, sysEvents, pageNumber, sysEvents];

    NSAppleScript *script = [[[NSAppleScript alloc] initWithSource:source] autorelease];
    [script executeAndReturnError:nil];
}

Here's what this does:

  • Call openFile: on an NSWorkspace instance
  • Open the Go to Page dialog of Preview
  • Wait for the dialog to pop up
  • Simulate the keypress of the page that should get activated, then press return

You can then call the method like so:

[[NSWorkspace sharedWorkspace] openPreviewFile:@"/YOUR_PDF.pdf"
                                        onPage:3];

Disclaimer: This breaks if the user defines a custom keyboard shortcut for the "Go to Page..." menu item!

like image 95
lemonmojo Avatar answered Oct 27 '22 18:10

lemonmojo