使用 Cocoa 打印本地 HTML
我有一个需要使用 Cocoa 打印的简单项目列表。我有一个不成熟的解决方案,它使用带有自定义 drawRect:
方法的 NSView,但它相当复杂并且不太容易维护。
我想要的是一个 HTML 字符串(可以很容易地从列表中构造),它可以嵌入一次性 WebView 中,然后打印。
假设我有一个简单的 NSString,例如:
NSString *htmlString = @"<b>Test</b>";
创建显示此内容的 WebView 的最简单方法是什么?我已经尝试过以下代码,但它会导致一个空白页:
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];
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];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您提出后立即解决的另一个问题!
运行循环需要迭代才能实际加载内容。我只是在框架加载委托方法中完成了实际的打印操作:
来源
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:
Source