How do i convert NSAttributedString into HTML string?
Asked Answered
B

3

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
Braze answered 14/3, 2011 at 11:54 Comment(2)
The title asks how to convert HTML into NSAttributeString, while the question does vice-versa.Racket
What exactly is the problem with the code you've posted? It should work.Cleft
C
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];
Cleft answered 4/1, 2013 at 21:13 Comment(9)
If the text contains link, than it wont create a href for the link.Materi
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?Matador
@Matador . did u find the solution for getting HTML tags for bold italic & underlineBeatriz
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 doubledCreel
Has anyone found a way to get cleaner/custom HTML out of the NSAttributedString.DocumentType.html conversion?Emunctory
@CliftonLabrum hi did you find an answer?Causation
@Causation 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.Emunctory
@CliftonLabrum thanks for sharing! how do you convert between markdown and nsattributedstring?Causation
@Causation I'm using SwiftyMarkdown: github.com/SimonFairbairn/SwiftyMarkdown. I modified it a bit to do what I needed, but it works pretty well.Emunctory
L
13

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
        }
    }
}
Lawannalawbreaker answered 16/6, 2018 at 20:2 Comment(0)
L
0

This should help to get the html string from Attributed String.

- (NSString *)htmlStringFromAttributedString:(NSAttributedString *)attributedString {
    NSMutableString *htmlString = [NSMutableString string];
    [htmlString appendString:@"<html><head></head><body>"];

    [attributedString enumerateAttributesInRange:NSMakeRange(0, attributedString.length) options:0 usingBlock:^(NSDictionary<NSAttributedStringKey,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
        NSString *text = [attributedString.string substringWithRange:range];
        
        // Start building HTML tags based on attributes
        if (attrs[NSFontAttributeName]) {
            UIFont *font = attrs[NSFontAttributeName];
            if ([font.fontName rangeOfString:@"Bold"].location != NSNotFound) {
                [htmlString appendString:@"<strong>"];
            }
            if ([font.fontName rangeOfString:@"Italic"].location != NSNotFound) {
                [htmlString appendString:@"<em>"];
            }
            if ([font.fontName rangeOfString:@"Oblique"].location != NSNotFound) {
                [htmlString appendString:@"<i>"];
            }
        }
        if (attrs[NSUnderlineStyleAttributeName]) {
            [htmlString appendString:@"<u>"];
        }

        // Append text
        [htmlString appendString:text];

        // Close HTML tags
        if (attrs[NSFontAttributeName]) {
            UIFont *font = attrs[NSFontAttributeName];
            if ([font.fontName rangeOfString:@"Bold"].location != NSNotFound) {
                [htmlString appendString:@"</strong>"];
            }
            if ([font.fontName rangeOfString:@"Italic"].location != NSNotFound) {
                [htmlString appendString:@"</em>"];
            }
            if ([font.fontName rangeOfString:@"Oblique"].location != NSNotFound) {
                [htmlString appendString:@"</i>"];
            }
        }
        if (attrs[NSUnderlineStyleAttributeName]) {
            [htmlString appendString:@"</u>"];
        }
    }];

    [htmlString appendString:@"</body></html>"];
    return htmlString;
}
Ludivinaludlew answered 6/5, 2024 at 9:1 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.