/*
Parse some HTML data, and adjust the attributes
Original Source:
(See copyright notice at )
*/
/*" Attempts to load the data as an HTML string as an attributed string, given the given attributes. We assume that the basis fonts that we are converting from are 12 point times family, and Monaco for monospaced. Monaco isn't changed to another font, but all other fonts are. Note that this doesn't work when the HTML has a table view in it, due to the way that these are handled as private classes in Apple's frameworks.
You pass in an attributes dictionary, something like [NSDictionary dictionaryWithObjectsAndKeys:[NSFont fontWithName:@"Garamond" size:18.0], NSFontAttributeName, nil], and the character encoding (e.g. NSASCIIStringEncoding) that the HTML data is expected to be in.
"*/
- (NSAttributedString *) parseHTMLWithAttributes:(NSDictionary *)inAttributes encoding:(NSStringEncoding) inEncoding
{
NSDictionary *encodingDict = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:inEncoding] forKey:@"CharacterEncoding"];
NSMutableAttributedString *result = [[[NSMutableAttributedString alloc]
initWithHTML:self documentAttributes:&encodingDict] autorelease];
NSFont *givenFont = [inAttributes objectForKey:NSFontAttributeName];
[result beginEditing];
if (nil != givenFont)
{
NSRange range;
NSFontManager *fontManager = [NSFontManager sharedFontManager];
NSString *family = [givenFont familyName];
range = NSMakeRange(0,0);
while(NSMaxRange(range) < [result length])
{
NSDictionary *attributes = [result attributesAtIndex:NSMaxRange(range) effectiveRange:&range];
NSFont *font = [attributes objectForKey:NSFontAttributeName];
// Change the font family, unless it's monospaced.
if (![[font familyName] isEqualToString:@"Monaco"])
{
font = [fontManager convertFont:font toFamily:family];
}
// Adjust the size. Calculate by percentages relative to 12, the base size.
float relativeSize = [font pointSize] / 12.0;
float newSize = (int) 0.5 + ([givenFont pointSize] * relativeSize);
font = [fontManager convertFont:font toSize:newSize];
[result addAttribute:NSFontAttributeName value:font range:range];
}
}
// Now add the rest of the attributes to the whole range
{
NSMutableDictionary *nonFontAttributes = [NSMutableDictionary dictionaryWithDictionary:inAttributes];
[nonFontAttributes removeObjectForKey:NSFontAttributeName];
if (0 != [nonFontAttributes count])
{
[result addAttributes:nonFontAttributes range:NSMakeRange(0, [result length])];
}
}
[result endEditing];
return result;
}