You can read RTF files into attributed strings, and vice-versa, in a couple of ways. Notice that although NSAttributedString belongs to Foundation framework, the methods for dealing with RTF data are defined in AppKit framework, so you need the appropriate use
statement.
First, the code for reading. Here we read the file as raw data, and create an attributed string from that.
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit" -- needed for used rtf methods
-- classes, constants, and enums used
property NSData : a reference to current application's NSData
property NSAttributedString : a reference to current application's NSAttributedString
property NSDictionary : a reference to current application's NSDictionary
property NSString : a reference to current application's NSString
property NSRTFTextDocumentType : a reference to current application's NSRTFTextDocumentType
set posixPath to POSIX path of (choose file with prompt "Choose an RTF file" of type {"rtf"})
-- read file as RTF data
set theData to NSData's dataWithContentsOfFile:posixPath
-- create attributed string from the data
set {theStyledString, docAttributes} to NSAttributedString's alloc()'s initWithRTF:theData documentAttributes:(reference)
if theStyledString is missing value then error "Could not read RTF file"
The variable docAttributes contains extra information about the document that can be used to create a new file, but itās optional.
Letās change the string by inserting a line at the beginning:
-- make copy you can modify
set theStyledString to theStyledString's mutableCopy()
-- insert text at beginning
theStyledString's replaceCharactersInRange:{0, 0} withString:("Extra text" & linefeed)
To save the modified attributed string you need to create RTF data from it, and then write the data to a file as you would any other data:
-- first turn attributed string into RTF data
set theData to theStyledString's RTFFromRange:{0, theStyledString's |length|()} documentAttributes:docAttributes
-- build path for new file
set posixPath to NSString's stringWithString:posixPath
set newPath to (posixPath's stringByDeletingPathExtension()'s stringByAppendingString:"-copy")'s stringByAppendingPathExtension:(posixPath's pathExtension())
-- write the data to the file
theData's writeToFile:newPath atomically:true
If you are creating a file from scratch, you wonāt have the docAttributes value. You can create it like this:
set docAttributes to {DocumentType:NSRTFTextDocumentType}