1

我正在尝试使用脚本桥来告诉 Safari 将当前页面保存为 PDF

在“Safari.h”头文件中存在一个SafariItem类的保存方法:

- (void) saveAs:(NSString *)as in:(NSURL *)in_;

所以我使用了这个,但它不起作用:

[safariCurrentTab saveAs:@".PDF" in:filePath];

后来我注意到safari.app的打印选项里有另存为PDF,所以我尝试使用这个功能

- (void) print:(NSURL *)x printDialog:(BOOL)printDialog withProperties:(SafariPrintSettings *)withProperties;

但是,当我尝试初始化一个 SafariPrintSettings 对象时,它导致了编译错误:

Undefined symbols for architecture x86_64:
"_OBJC_CLASS_$_SafariPrintSettings", referenced from:
  objc-class-ref in AppDelegate.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

似乎编译器没有找到那个类,但我确实包含了头文件并添加了 ScriptingBridge 框架

任何人都可以帮忙吗?

提前致谢。

4

1 回答 1

2

所以既不saveAs:也不SafariPrintSettings行。

Safari 应用程序中的“另存为...”功能仅提供 HTML,而 Scripting Bridge 只会为您提供这些选项。这是要记住的事情:Scripting Bridge 是一种自动化您将在界面中执行的操作的方法。

“打印到 PDF”除外。没有用于生成 PDF 的打印机对象。OS X 调用一个(或多个,很难说)实用程序将 HTML 转换为 PDF。

可能的解决方案使用NSTask

/System/Libary/Printers/Libraries/你会发现(不要与convert系统范围的 ImageMagick 转换混淆......它们不一样!)。如果你想走这条路,你必须先将页面保存为 HTML 文件,然后你可以使用它NSTask来运行convert命令,如下所示:

NSTask *convert = [[NSTask alloc] init];
[convert setLaunchPath:@"/System/Libary/Printers/Libraries/convert"];
[convert setArguments:[NSArray arrayWithObjects:@"-f",@"fileYouSaved.html",@"-o","foo.pdf",nil]];
//set output and so on...
[convert launch];
//this runs the command as if it were "convert -f fileYouSaved.html -o foo.pdf"

But it seems flaky; some elements were left hanging off the "printable" page on some of the wider websites I tried.

Easiest possible solution

There is a third-party command line app/Ruby gem that might remove a lot of work called wkpdf. You would simply execute:

wkpdf --source http://www.apple.com --output apple.pdf

and it would grab the page online and do what you need. Alternatively, once you've installed it on your system, you can also call it in your app using NSTask, if you have more steps you need to take with the PDF file.

You can find wkpdf here: http://plessl.github.com/wkpdf/

于 2012-07-14T01:28:28.247 回答