27

As the title tells,now i can simple convert HTML into NSAttributedString with initWithHTML:documentAttributes: , but what i want to do here is reverse. Is there any 3rd party library to achieve this?

   @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
Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
NeXT5tep
  • 861
  • 1
  • 11
  • 23

2 Answers2

45

Use dataFromRange:documentAttributes: with the document type attribute (NSDocumentTypeDocumentAttribute) set to 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];
ChikabuZ
  • 10,031
  • 5
  • 63
  • 86
omz
  • 53,243
  • 5
  • 129
  • 141
  • If the text contains link, than it wont create a href for the link. – Balazs Nemeth Mar 09 '15 at 11:27
  • 12
    I just need Bold, Italic, Underline & StrikeThrough tags in my HTML but converting NSAttributedString to HTML outputs a lot of css to achieve this. Any alternative to keep this simple? – ilight Feb 09 '16 at 07:38
  • @ilight . did u find the solution for getting HTML tags for bold italic & underline – Uma Madhavi Jun 06 '17 at 07:57
  • The biggest problem that i am facing is, when i am using this, the font size of the content is getting increased, why i dont know but it almost getting doubled – Mehul Thakkar Jun 22 '17 at 07:35
  • 1
    Has anyone found a way to get cleaner/custom HTML out of the `NSAttributedString.DocumentType.html` conversion? – Clifton Labrum Nov 16 '17 at 21:12
  • @CliftonLabrum hi did you find an answer? – Crashalot Dec 11 '18 at 15:25
  • @Crashalot Unfortunately not. That appears to be something Apple has long since abandoned. I decided to pursue a different path and use Markdown instead of HTML. – Clifton Labrum Dec 11 '18 at 17:05
  • @CliftonLabrum thanks for sharing! how do you convert between markdown and nsattributedstring? – Crashalot Dec 11 '18 at 17:13
  • @Crashalot I'm using **SwiftyMarkdown**: https://github.com/SimonFairbairn/SwiftyMarkdown. I modified it a bit to do what I needed, but it works pretty well. – Clifton Labrum Dec 11 '18 at 21:14
11

This is a swift 4 conversion of @omz answer, hope is useful to anyone landing here

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
        }
    }
}
Stickley
  • 4,561
  • 3
  • 30
  • 29
Daniele Bernardini
  • 1,516
  • 1
  • 12
  • 29