Question

I am trying to use the scripting-bridge to tell Safari to save the current page as PDF

In the "Safari.h" header file exists a saving method of SafariItem class:

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

So I used this but it doesn't work:

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

Later I noticed that saving as PDF is in the print option in Safari.app, so I tried to use this function

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

However when I tried to init a SafariPrintSettings object, it caused compile error:

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)

Seems that the compiler doesn't find that class, but I did include the header file and add the ScriptingBridge framework

Anyone can help?

Thanks in advance.

Was it helpful?

Solution

So neither saveAs: nor SafariPrintSettings will work.

The "Save As..." functionality in the Safari app only provides HTML, and Scripting Bridge will only provide you with those options. That's the thing to keep in mind: Scripting Bridge is a way to automate things you would do in the interface.

Except for "printing to PDF". There is no printer object for producing PDFs. OS X calls upon one (or many, it's hard to say) utilities to convert the HTML to PDF.

Possible solution using NSTask

In /System/Libary/Printers/Libraries/ you'll find convert (which is not to be confused with the system-wide ImageMagick convert... they're not the same!). If you wanted to go this route, you'd have to save the page as an HTML file first, then you could use NSTask to run the convert command, like so:

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/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top