Skip to content

Instantly share code, notes, and snippets.

@orta
Created October 23, 2013 12:36
Show Gist options
  • Save orta/7117853 to your computer and use it in GitHub Desktop.
Save orta/7117853 to your computer and use it in GitHub Desktop.
HTML -> NSAttributedString using only UIKit
+ (NSAttributedString *)artsyBodyTextAttributedStringFromHTML:(NSString *)HTML withFont:(UIFont *)font
{
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
style.lineHeightMultiple = 1.2;
style.paragraphSpacing = font.pointSize * .5;
NSDictionary *textParams = @{
NSFontAttributeName : font,
NSParagraphStyleAttributeName : style,
NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle)
};
return [self _attributedStringWithTextParams:textParams andHTML:HTML];
}
+ (NSString *)_cssStringFromAttributedStringAttributes:(NSDictionary *)dictionary
{
NSMutableString *cssString = [NSMutableString stringWithString:@"<style> p {"];
if ([dictionary objectForKey:NSFontAttributeName]) {
UIFont *font = dictionary[NSFontAttributeName];
[cssString appendFormat:@"font-family:'%@'; font-size: %0.fpx;", font.fontName, roundf(font.pointSize)];
}
if (dictionary[NSParagraphStyleAttributeName]) {
NSParagraphStyle *style = dictionary[NSParagraphStyleAttributeName];
[cssString appendFormat:@"line-height:%0.1f em;", style.lineHeightMultiple];
}
[cssString appendString:@"}"];
[cssString appendString:@"</style><body>"];
return cssString;
}
+ (NSAttributedString *)_attributedStringWithTextParams:(NSDictionary *)textParams andHTML:(NSString *)HTML
{
NSDictionary *importParams = @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType };
NSError *error = nil;
NSString *formatString = [[self _cssStringFromAttributedStringAttributes:textParams] stringByAppendingFormat:@"%@</body>", HTML];
NSData *stringData = [formatString dataUsingEncoding:NSUnicodeStringEncoding] ;
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:stringData options:importParams documentAttributes:NULL error:&error];
if (error) {
ARErrorLog(@"Error creating NSAttributedString from HTML %@", error.localizedDescription);
return nil;
}
return attributedString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment