是否可以在特定页面上使用Preview.app打开PDF?

goe*_*etz 5 macos cocoa

我可以path使用我的应用程序中的Preview.app 开心地打开PDF文件

[NSWorkspace.sharedWorkspace openFile: path];
Run Code Online (Sandbox Code Playgroud)

但是,我想在某个页面上使用该文件启动Preview.app.这是可能的,例如通过将特定NSAppleEventDescriptorNSWorkspace

- (BOOL)openURLs:(NSArray *)urls withAppBundleIdentifier:(NSString *)bundleIdentifier options:(NSWorkspaceLaunchOptions)options additionalEventParamDescriptor:(NSAppleEventDescriptor *)descriptor launchIdentifiers:(NSArray **)identifiers
Run Code Online (Sandbox Code Playgroud)

方法?QuickLook可以做到这一点,我想模仿这种行为.

谢谢你的帮助!

lem*_*ojo 3

您可以通过 NSAppleScript 来完成此操作。

下面是一个打开文件并跳转到指定页面的 NSWorkspace 类别方法:

- (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];
}
Run Code Online (Sandbox Code Playgroud)

这是它的作用:

  • 在 NSWorkspace 实例上调用 openFile:
  • 打开预览的转到页面对话框
  • 等待对话框弹出
  • 模拟应该激活的页面的按键,然后按回车键

然后您可以像这样调用该方法:

[[NSWorkspace sharedWorkspace] openPreviewFile:@"/YOUR_PDF.pdf"
                                        onPage:3];
Run Code Online (Sandbox Code Playgroud)

免责声明:如果用户为“转到页面...”菜单项定义自定义键盘快捷键,则会中断!