使用 Cocoa 打印本地 HTML

发布于 2024-12-05 23:41:42 字数 925 浏览 0 评论 0原文

我有一个需要使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萌化 2024-12-12 23:41:42

您提出后立即解决的另一个问题!

运行循环需要迭代才能实际加载内容。我只是在框架加载委托方法中完成了实际的打印操作:

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

来源

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文