我是一个QT程序员,Cocoa对我来说是新的。如何可以转换富文本格式(RTF文本与图像和超链接)到HTML使用可可在Mac OS X。我有丰富的文本到一个字符类型缓冲区。
发布于 2014-01-05 01:23:51
使用RTF数据创建一个NSAttributedString实例。遍历字符串的属性范围(包括附件/图片)并将其转换为超文本标记语言(将适当的超文本标记语言附加到NSMutableString)。这使您可以转换任何您想要的属性,同时保留那些您不需要的属性。
-enumerateAttributesInRange:options:usingBlock:是一个有用的NSAttributedString方法。在块中,您可以决定是否要处理或忽略给定的属性。有关处理图像的信息,请参阅Handling Attachments部分(在RTFD中被视为附件,只是属性字符串中“字符”的另一种属性类型)。
发布于 2014-01-05 11:26:06
您可以使用NSAttributedString和Application Kit - read NSAttributedString Application Kit Additions Reference提供的附加功能来执行RTF到HTML的转换。
这些是从RTF创建NSAttributedString的方法,例如initWithRTF:documentAttributes:和initWithURL:documentAttributes:。
要创建超文本标记语言,您可以使用dataFromRange:documentAttributes:error:指定适当的属性,您至少需要指定NSHTMLTextDocumentType。
发布于 2014-01-05 03:19:19
取决于您的输出要求…我可以将字符串"hello world“转换为有效的html,但它可能不是您所期望的…。无论如何,作为@Joshua的…的替代方法
textutil实用程序对所有类型的转换都很有用。您可以通过NSTask从Cocoa使用它
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath: @"/usr/bin/textutil"];
[task setArguments: @[@"-format", @"rtf", @"-convert", @"html", @"-stdin", @"-stdout"]];
[task setStandardInput:[NSPipe pipe]];
[task setStandardOutput:[NSPipe pipe]];
NSFileHandle *taskInput = [[task standardInput] fileHandleForWriting];
[taskInput writeData:[NSData dataWithBytes:cString length:cStringLength]];
[task launch];
[taskInput closeFile];同步
NSData *outData = [[[task standardOutput] fileHandleForReading] readDataToEndOfFile];
NSString *outStr = [[NSString alloc] initWithData:outData encoding:NSUTF8StringEncoding];或异步
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(readCompleted:) name:NSFileHandleReadToEndOfFileCompletionNotification object:[[task standardOutput] fileHandleForReading]];
[[[task standardOutput] fileHandleForReading] readToEndOfFileInBackgroundAndNotify];
- (void)readCompleted:(NSNotification *)notification {
NSData *outData = [[notification userInfo] objectForKey:NSFileHandleNotificationDataItem];
NSString *outStr = [[NSString alloc] initWithData:outData encoding:NSUTF8StringEncoding];
NSLog(@"Read data: %@", outStr);
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSFileHandleReadToEndOfFileCompletionNotification object:[notification object]];
}但是,请不要只是复制和粘贴..这只是一个例子,并没有经过测试的产品代码。
https://stackoverflow.com/questions/20923730
复制相似问题