如何将NSAttributedString转换为HTML字符串?

NeX*_*tep 26 html cocoa nsattributedstring

正如标题所说,现在我可以简单地将HTML转换NSAttributedStringinitWithHTML:documentAttributes:,但我想在这里做的是反向.是否有任何第三方库来实现这一目标?

   @implementation NSAttributedString(HTML)
-(NSString *)htmlForAttributedString{
    NSArray * exclude = [NSArray arrayWithObjects:@"doctype",
                         @"html",
                         @"head",
                         @"body",
                         @"xml",
                         nil
                         ];
    NSDictionary * htmlAtt = [NSDictionary
                              dictionaryWithObjectsAndKeys:NSHTMLTextDocumentType,
                              NSDocumentTypeDocumentAttribute,
                              exclude,
                              NSExcludedElementsDocumentAttribute,
                              nil
                              ];
    NSError * error;
    NSData * htmlData = [self dataFromRange:NSMakeRange(0, [self length])
                               documentAttributes:htmlAtt error:&error
                         ];
        //NSAttributedString * htmlString = [[NSAttributedString alloc]initWithHTML:htmlData documentAttributes:&htmlAtt];
    NSString * htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];
    return htmlString;
}
@end
Run Code Online (Sandbox Code Playgroud)

omz*_*omz 44

使用dataFromRange:documentAttributes:与文档类型属性(NSDocumentTypeDocumentAttribute)设置为HTML( NSHTMLTextDocumentType):

NSAttributedString *s = ...;
NSDictionary *documentAttributes = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};    
NSData *htmlData = [s dataFromRange:NSMakeRange(0, s.length) documentAttributes:documentAttributes error:NULL];
NSString *htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];
Run Code Online (Sandbox Code Playgroud)

  • 我只需要在我的HTML中使用Bold,Italic,Underline和StrikeThrough标签,但将NSAttributedString转换为HTML会输出大量的css来实现这一点.保持这个简单的任何替代方案? (9认同)

Dan*_*ini 5

这是@omz答案的快速4转换,希望对登陆此处的任何人都有用

extension NSAttributedString {
    var attributedString2Html: String? {
        do {
            let htmlData = try self.data(from: NSRange(location: 0, length: self.length), documentAttributes:[.documentType: NSAttributedString.DocumentType.html]);
            return String.init(data: htmlData, encoding: String.Encoding.utf8)
        } catch {
            print("error:", error)
            return nil
        }
    }
}
Run Code Online (Sandbox Code Playgroud)