Apply Custom Font to Attributed String Which Converts from HTML String

Apply Custom font to Attributed string Which Converts from HTML String

Finally i got answer. you can check larmes answer(Find attributes from attributed string that user typed) or you can simply remove old font attribute and apply new font using below code.

 NSDictionary *dictAttrib = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,  NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)};
NSMutableAttributedString *attrib = [[NSMutableAttributedString alloc]initWithData:[yourHTMLString dataUsingEncoding:NSUTF8StringEncoding] options:dictAttrib documentAttributes:nil error:nil];
[attrib beginEditing];
[attrib enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, attrib.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
if (value) {
UIFont *oldFont = (UIFont *)value;
NSLog(@"%@",oldFont.fontName);

/*----- Remove old font attribute -----*/
[attrib removeAttribute:NSFontAttributeName range:range];
//replace your font with new.
/*----- Add new font attribute -----*/
if ([oldFont.fontName isEqualToString:@"TimesNewRomanPSMT"])
[attrib addAttribute:NSFontAttributeName value:font1 range:range];
else if([oldFont.fontName isEqualToString:@"TimesNewRomanPS-BoldMT"])
[attrib addAttribute:NSFontAttributeName value:font2 range:range];
else if([oldFont.fontName isEqualToString:@"TimesNewRomanPS-ItalicMT"])
[attrib addAttribute:NSFontAttributeName value:font3 range:range];
else if([oldFont.fontName isEqualToString:@"TimesNewRomanPS-BoldItalicMT"])
[attrib addAttribute:NSFontAttributeName value:font4 range:range];
else
[attrib addAttribute:NSFontAttributeName value:font5 range:range];
}
}];
[attrib endEditing];

Thanks. Maybe it will help you.

How to set custom font with regular and bold font while setting html string to label in swift 4?

This should help :

extension String {

func attributedString(withRegularFont regularFont: UIFont, andBoldFont boldFont: UIFont) -> NSMutableAttributedString {
var attributedString = NSMutableAttributedString()
guard let data = self.data(using: .utf8) else { return NSMutableAttributedString() }
do {
attributedString = try NSMutableAttributedString(data: data,
options: [.documentType: NSAttributedString.DocumentType.html,
.characterEncoding:String.Encoding.utf8.rawValue],
documentAttributes: nil)
let range = NSRange(location: 0, length: attributedString.length)
attributedString.enumerateAttribute(NSAttributedString.Key.font, in: range, options: .longestEffectiveRangeNotRequired) { value, range, _ in
let currentFont: UIFont = value as! UIFont
var replacementFont: UIFont? = nil

if currentFont.fontName.contains("bold") || currentFont.fontName.contains("Bold") {
replacementFont = boldFont
} else {
replacementFont = regularFont
}

let replacementAttribute = [NSAttributedString.Key.font:replacementFont!]
attributedString.addAttributes(replacementAttribute, range: range)
}
} catch let e {
print(e.localizedDescription)
}
return attributedString
}
}

Swift- Change font on an HTML string that has its own Styles

The setAttributes will reset all the attributes from HTML. I wrote an extension method to avoid this:

Swift 4

public convenience init?(HTMLString html: String, font: UIFont? = nil) throws {
let options : [NSAttributedString.DocumentReadingOptionKey : Any] =
[NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html,
NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue]

guard let data = html.data(using: .utf8, allowLossyConversion: true) else {
throw NSError(domain: "Parse Error", code: 0, userInfo: nil)
}

if let font = font {
guard let attr = try? NSMutableAttributedString(data: data, options: options, documentAttributes: nil) else {
throw NSError(domain: "Parse Error", code: 0, userInfo: nil)
}
var attrs = attr.attributes(at: 0, effectiveRange: nil)
attrs[NSAttributedStringKey.font] = font
attr.setAttributes(attrs, range: NSRange(location: 0, length: attr.length))
self.init(attributedString: attr)
} else {
try? self.init(data: data, options: options, documentAttributes: nil)
}
}

Test sample:

let html = "<html><body><h1 style=\"color:red;\">html text here</h1></body></html>"
let font = UIFont.systemFont(ofSize: 16)

var attr = try NSMutableAttributedString(HTMLString: html, font: nil)
var attrs = attr?.attributes(at: 0, effectiveRange: nil)
attrs?[NSAttributedStringKey.font] as? UIFont
// print: <UICTFont: 0x7ff19fd0a530> font-family: "TimesNewRomanPS-BoldMT"; font-weight: bold; font-style: normal; font-size: 24.00pt

attr = try NSMutableAttributedString(HTMLString: html, font: font)
attrs = attr?.attributes(at: 0, effectiveRange: nil)
attrs?[NSAttributedStringKey.font] as? UIFont
// print: <UICTFont: 0x7f8c0cc04620> font-family: ".SFUIText"; font-weight: normal; font-style: normal; font-size: 16.00pt

How change the font of attributed string in iOS?

Try with this:

NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[inst.desc dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
NSMutableAttributedString *newString = [[NSMutableAttributedString alloc] initWithAttributedString:attributedString];
NSRange range = (NSRange){0,[newString length]};
[newString enumerateAttribute:NSFontAttributeName inRange:range options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id value, NSRange range, BOOL *stop) {
UIFont *replacementFont = [UIFont fontWithName:@"Palatino-Roman" size:14.0];
[newString addAttribute:NSFontAttributeName value:replacementFont range:range];
}];
self.label.attributedText = newString;

Parsing HTML into NSAttributedText - how to set font?

Figured it out. Bit of a bear, and maybe not the best answer.

This code will go through all the font changes. I know that it is using "Times New Roman" and "Times New Roman BoldMT" for the fonts.
But regardless, this will find the bold fonts and let me reset them. I can also reset the size while I'm at it.

I honestly hope/think there is a way to set this up at parse time, but I can't find it if there is.

- (void)changeFont:(NSMutableAttributedString*)string
{
NSRange range = (NSRange){0,[string length]};
[string enumerateAttribute:NSFontAttributeName inRange:range options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id value, NSRange range, BOOL *stop) {
UIFont* currentFont = value;
UIFont *replacementFont = nil;

if ([currentFont.fontName rangeOfString:@"bold" options:NSCaseInsensitiveSearch].location != NSNotFound) {
replacementFont = [UIFont fontWithName:@"HelveticaNeue-CondensedBold" size:25.0f];
} else {
replacementFont = [UIFont fontWithName:@"HelveticaNeue-Thin" size:25.0f];
}

[string addAttribute:NSFontAttributeName value:replacementFont range:range];
}];

}

Swift - Font size increases when converting html string to attributed string and back again

Try this method I found from some help and then converted to Swift 3:

func newAttrSize(blockQuote: NSAttributedString) -> NSAttributedString
{
let yourAttrStr = NSMutableAttributedString(attributedString: blockQuote)
yourAttrStr.enumerateAttribute(.font, in: NSMakeRange(0, yourAttrStr.length), options: .init(rawValue: 0)) {
(value, range, stop) in
if let font = value as? UIFont {
let resizedFont = font.withSize(font.pointSize * 0.75)
yourAttrStr.addAttribute(.font, value: resizedFont, range: range)
}
}

return yourAttrStr
}


Related Topics



Leave a reply



Submit