Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print Local HTML using Cocoa

I have a simple list of items that needs to be printed using Cocoa. I have a half-baked solution that uses an NSView with a custom drawRect: method, but it's fairly complex and not very easy to maintain.

What I would like to have is an HTML string (which could be easily constructed from the list) that can be embedded in a one-off WebView, then printed.

Assuming I have a simple NSString like:

NSString *htmlString = @"<b>Test</b>";

What's the easiest method for creating a WebView displaying this content? I've tried the below code, but it results in a single blank page:

WebView *webView = [[WebView alloc] init];
NSString *dir = @"/Users/Me/Desktop/";
NSString *fileUrl = [dir stringByAppendingPathComponent:@"Temp_Print.html"];

NSString *htmlString = @"<b>Hi!</b>";
[[htmlString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileUrl atomically:YES];

[[webView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:fileUrl]]];
[webView setFrame:NSMakeRect(0, 0, 500, 500)];
NSPrintOperation *po = [NSPrintOperation printOperationWithView:webView printInfo:pi];

[pi release];
[po runOperation];
like image 222
Craig Otis Avatar asked Oct 09 '22 22:10

Craig Otis


1 Answers

Another one of those questions you solve right after asking it!

The run loop needs to iterate in order for the content to actually load. I simply finished running the actual print operation in the frame load delegate method:

- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
   ...
}

Source

like image 88
Craig Otis Avatar answered Oct 18 '22 15:10

Craig Otis