我正在尝试将 html 数据复制到 MAC 上的剪贴板。但是当我使用(Finder-> Edit Menu -> Show clipboard)检查剪贴板时,它什么也没显示。我希望按原样粘贴格式化的数据。以下是我正在使用的代码:
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/)上粘贴颜色?