首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将HTML数据写入NSPasteboard

将HTML数据写入NSPasteboard
EN

Stack Overflow用户
提问于 2013-11-29 17:03:28
回答 2查看 977关注 0票数 2

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

代码语言:javascript
复制
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/ )中粘贴数据时,它会丢失一些格式,如颜色。

代码语言:javascript
复制
 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/)上粘贴颜色呢?

EN

回答 2

Stack Overflow用户

发布于 2013-12-02 13:40:02

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

票数 0
EN

Stack Overflow用户

发布于 2013-11-29 17:36:06

编辑

如果您想复制它并应用属性,则使用

代码语言:javascript
复制
NSAttributedString *attrString = [[NSAttributedString alloc] initWithHTML:@"YOUR HTML CODE" documentAttributes:NULL];
[pb setData:attrString forType: NSPasteboardTypeRTF];
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20281814

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档