以编程方式创建RTFD

时间:2014-05-13 16:49:24

标签: objective-c macos file-io

我正在尝试创建一个包含文本(NSString)和图像(JPG)的RTFD文件。我没有找到一个简单易懂的例子来解释这个过程。如果我的应用程序有一些文本和一些JPG图像,并且我想创建一个包含这两个项目的可编辑文档,RTFD似乎是输出的最佳选择(我想保留图像的质量)。

如果有人可以提供一个简单的示例,说明如何处理有用的文本和图像。只要图像质量得以保留,我也愿意做RTF。这适用于Mac OS应用程序。

我一直在尝试关注Attributed String Programming Guide,但我不清楚如何输出NSAttributedString并创建捆绑包。其次,我如何将图像引用不仅包括RTF文件,还包括它们需要的包。

1 个答案:

答案 0 :(得分:1)

相当陈旧的问题,但也许解决方案可以帮助其他人......

RTFD格式不描述文件,而是描述文件包(实际上是由Mac / iOS UI修改的目录,以便将用户显示为单个文件)。

但幸运的是, NSFileWrapper 能够创建此类RTFD包:

NSAttributedString* attrString = ...some attributed string with images ...;
NSDictionary*       documentAttributes = @{
                                           NSDocumentTypeDocumentAttribute: NSRTFDTextDocumentType
                                           };
NSError*            error = nil;
NSFileWrapper*      fileWrapper = [attrString fileWrapperFromRange:NSMakeRange(0, attrString.length)
                                            documentAttributes:documentAttributes
                                                         error:&error];

NSString*           documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString*           filePath = [documentsDirectory stringByAppendingPathComponent:@"example.rtfd"];
NSLog(@"Writing rtfd doc to: %@", filePath);

[NSFileManager.defaultManager removeItemAtPath:filePath error:&error];
BOOL    result = [fileWrapper writeToURL:[NSURL fileURLWithPath:filePath]
                              options:NSFileWrapperWritingAtomic
                  originalContentsURL:nil
                                error:&error];

完成!

由于RTFD几乎只是Mac / iOS格式,因此创建包含图像的RTF文件可能会更有趣。

不幸的是,Apple的RTF实现(NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType)不支持图像。

请参阅我对另一个问题的回答来解决此问题:https://stackoverflow.com/a/29181130/2778898

相关问题