html - 将 HTML 数据写入 NSPasteboard

标签 html objective-c macos cocoa nspasteboard

我正在尝试将 html 数据复制到 MAC 上的剪贴板。但是当我使用(Finder->编辑菜单->显示剪贴板)检查剪贴板时,它什么也不显示。我希望按原样粘贴格式化数据。下面是我正在使用的代码:

NSPasteboard *pb = [NSPasteboard generalPasteboard];
NSAttributedString *htmlString = [[NSAttributedString alloc]initWithString:@"<html><body><b>abcdefgh</b></body></html>"];
NSDictionary *documentAttributes = [NSDictionary dictionaryWithObjectsAndKeys:NSHTMLTextDocumentType, NSDocumentTypeDocumentAttribute, nil];
NSData *htmlData = [htmlString dataFromRange:NSMakeRange(0, htmlString.length) documentAttributes:documentAttributes error:NULL];

[pb declareTypes:[NSArray arrayWithObject:NSHTMLPboardType] owner:nil];
[pb setData:htmlData forType:NSHTMLPboardType];

我将不胜感激任何帮助。谢谢!

更新:

为了在剪贴板中获取html格式的字符串,我尝试将其转换为属性字符串,然后从属性字符串转换为rtf数据,它将数据完美地设置到剪贴板,但是当我尝试将数据粘贴到html编辑器中时(http://htmleditor.in/) )它会丢失一些格式,例如颜色。

 NSPasteboard *pb = [NSPasteboard generalPasteboard];
 NSString *htmlString = @"<HTML> <BODY> <P><FONT COLOR=\"RED\"><UL><LI>fhhj</LI><LI>juil</LI></UL><B>hello</B> <i>html</i></FONT></P> </BODY></HTML>";

NSDictionary *documentAttributes = [NSDictionary dictionaryWithObjectsAndKeys:NSHTMLTextDocumentType, NSDocumentTypeDocumentAttribute, NSCharacterEncodingDocumentAttribute,[NSNumber numberWithInt:NSUTF8StringEncoding], nil];

NSAttributedString* atr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding] options:documentAttributes documentAttributes:nil error:nil];

 NSData *rtf = [atr RTFFromRange:NSMakeRange(0, [atr length])
                                    documentAttributes:nil];

    [pb declareTypes:[NSArray arrayWithObject:NSRTFPboardType] owner:nil];
    [pb setData:rtf forType:NSRTFPboardType];

粘贴到 html 编辑器时如何保留颜色?文本在剪贴板上以颜色显示,那么为什么它在 html 编辑器上不以颜色粘贴(http://htmleditor.in/)?

最佳答案

我终于遇到了问题,该功能取决于浏览器(但我不明白原因)。 如果我在 Safari 中粘贴到该网站,它不会丢失任何格式并且运行良好,但如果我将相同的文本粘贴到 chrome 上的同一网站,它会丢失一些格式。

关于html - 将 HTML 数据写入 NSPasteboard,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20281814/

相关文章:

xcode - 附加到远程进程以进行调试

macos - 确定滚动条是覆盖式还是旧式

css - 如何在富文本编辑器中编辑ol标签

objective-c - horizo​​ntalAccuracy 究竟是什么意思?

objective-c - UIScrollView + UIImage 和缩放 : not fluid

ios - 在 iOS7 中,cell.selectedBackgroundView 没有显示

jquery - 检测何时滚动到面板内的 <ul> 最后一个 <li>

html - 如何使用 css 更改 html 表格中每个单词实例的颜色?

javascript - Contenteditable 在子节点上设置插入符号

macos - NSSearchField 有时会导致 NSInternalInconsistencyException