最近,我在我的项目中遇到了一个问题 . 我需要将NSAttributedString转换为HTML文件 . 解决方案单击here对我不起作用,因为要仅使用TagName和idName以及ClassName输出HTML文件,同时输出CSS样式文件以控制HTML文件的显示方式 . 这是我的示例代码,我希望你能得到我的意图:
- (NSDictionary *)html
{
NSTextStorage *textStorage = [self contents];
NSArray *arr = [textStorage paragraphs];
// Initialize the CSS dictionay
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
nil];
NSEnumerator *paragraphEnumerator;
paragraphEnumerator = [arr objectEnumerator];
NSAttributedString *paragraph;
NSMutableArray *paragrapHTMLStrings = [[NSMutableArray alloc] initWithCapacity:[arr count]];
NSMutableString *cssString = [[NSMutableString alloc] initWithCapacity:0];
[cssString appendString:@"div{"];
[cssString appendString:[NSString stringWithFormat:@"-webkit-column-count:%ld;", self.columnCount]];
[cssString appendString:[NSString stringWithFormat:@"width:%fpx;", self.bounds.size.width]];
[cssString appendString:[NSString stringWithFormat:@"height:%fpx;", self.bounds.size.height]];
[cssString appendString:@"}"];
[dict setObject:cssString forKey:@"css"];
while (paragraph = [paragraphEnumerator nextObject]) {
// initialize
NSUInteger length;
NSRange effectiveRange = NSMakeRange(0, 0);
id attributeValue;
length = [paragraph length];
// get the font attributes
attributeValue = [paragraph attribute:NSFontAttributeName atIndex:NSMaxRange(effectiveRange) effectiveRange:&effectiveRange];
NSLog(@"font is %@", [attributeValue fontName]);
NSLog(@"font-size is %f", [[[attributeValue fontDescriptor] objectForKey:NSFontSizeAttribute] floatValue]);
NSMutableString *htmlString = [NSMutableString stringWithFormat:@"", [attributeValue fontName],
[[[attributeValue fontDescriptor] objectForKey:NSFontSizeAttribute] floatValue]];
[htmlString appendString:[paragraph string]];
[htmlString appendString:@" "];
NSLog(@"htmlString is %@", htmlString);
[paragrapHTMLStrings addObject:htmlString];
htmlString = nil;
}
NSMutableString *htmlStringOfGraphToReturn = [NSMutableString stringWithString:@""];
NSString *stringToAdd;
NSEnumerator *stringEnumerator;
stringEnumerator = [paragrapHTMLStrings objectEnumerator];
while (stringToAdd = [stringEnumerator nextObject])
{
[htmlStringOfGraphToReturn appendString:stringToAdd];
}
[htmlStringOfGraphToReturn appendString:@""];
[dict setObject:htmlStringOfGraphToReturn forKey:@"html"];
// test part
CSSSetGenerator *generater = [[CSSSetGenerator alloc] init];
NSMutableString *string = [generater outputCSSStyleContent:self];
NSLog(@"%@", string);
return dict;
}
1 回答
我从Github得到了解决方案,有一个名为DTCoreText的开放项目 . 我希望这对某人有用 .