Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C - How to create rtf from NSAttributedString

I can convert from rtf string to attributed string using following:

 NSAttributedString *attributedStr = [[NSAttributedString alloc] initWithData:data options:@{NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType} documentAttributes:nil error:nil];

Now how can i convert back from attributedString to rtf string?

like image 972
Hassy Avatar asked Dec 07 '22 01:12

Hassy


1 Answers

You want to use -dataFromRange:documentAttributes:error:

NSAttributedString *str = [[NSAttributedString alloc] initWithString:@"YOLO" attributes:nil];
NSData *data = [str dataFromRange:(NSRange){0, [str length]} documentAttributes:@{NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType} error:NULL];
[data writeToFile:@"/me.rtf" atomically:YES];

Of course you'd want to have some attributes instead of "YOLO", but you get the idea.

Also, if you're looking to simply write this to disk, then fileWrapperFromRange:documentAttributes:error: might even be a better option. You can find more about reading and writing from the Attributed String Programming Guide

like image 198
Lucas Derraugh Avatar answered Dec 27 '22 11:12

Lucas Derraugh