Search code examples
macoscocoamergertf

Merging RTF Files With Cocoa


How would one do this? I know just merging NSData doesn't work.


Solution

  • Playing with NSAttributedString should work, something like the code shown below

    This is a very quick and dirty way to merge many RTF files together

    - (void)mergeRTF:(NSURL*)rtf1 :(NSURL*)rtf2 :(NSURL*)merged {
        NSMutableDictionary *options = [NSMutableDictionary dictionary];
        [options setObject:[NSNumber numberWithUnsignedInteger:NSUTF8StringEncoding]
                    forKey:NSCharacterEncodingDocumentOption];
        NSDictionary *docAttrs = nil;
        NSError* error = nil;
    
        NSAttributedString *rtfText1 = [[NSAttributedString alloc] initWithURL:rtf1
                                                                   options:options
                                                        documentAttributes:&docAttrs
                                                                     error:&error];
    
        NSAttributedString *rtfText2 = [[NSAttributedString alloc] initWithURL:rtf2
                                                                    options:options
                                                         documentAttributes:&docAttrs
                                                                      error:&error];
        NSMutableAttributedString* whole = [[NSMutableAttributedString alloc] initWithAttributedString:rtfText1];
        [whole appendAttributedString:rtfText2];
        NSData* data = [whole RTFFromRange:NSMakeRange(0, whole.length) documentAttributes:nil];
    
        [data writeToURL:merged atomically:YES];
    }