< Previous PageNext Page > Hide TOC

RTF Files and Attributed Strings

Rich Text Format (RTF) is a text formatting language devised by Microsoft Corporation. You can represent character, paragraph, and document format attributes using plain text with interspersed RTF commands, groups, and escape sequences. RTF is widely used as a document interchange format to transfer documents with their formatting information across applications and computing platforms. The Application Kit has support for reading and writing RTF. For text attributes not available in standard RTF, Apple has extended RTF with custom commands.

Contents:

Reading and Writing RTF Data
Apple’s RTF Extensions


Reading and Writing RTF Data

The Application Kit’s extensions for NSAttributedString add support for reading text attributes from, and writing them to, RTF files or RTFD (rich text with attachments) files.

Important: The Application Kit extensions write the standard character-level attributes from the attributed string and the standard document-level attributes from the document attributes dictionary; however, custom attributes that you define and add to an attributed string are not written to the RTF file. Standard character-level attribute keys are described in “Standard Attributes,” and the document attributes are described in Table 1.

The NSAttributedString methods for writing rich text are defined in NSAttributedString Application Kit Additions Reference:

RTFFromRange:documentAttributes:Returns an NSData object that contains an RTF stream corresponding to the characters and attributes within the given range, omitting all attachment attributes.
RTFDFromRange:documentAttributes:Returns an NSData object that contains an RTFD stream corresponding to the characters and attributes within aRange.
RTFDFileWrapperFromRange:documentAttributes:Returns an NSFileWrapper object that contains an RTFD document corresponding to the characters and attributes within the given range.
initWithRTF:documentAttributes:Initializes a new NSAttributedString object by decoding the stream of RTF commands and data contained in the given data object.
initWithRTFD:documentAttributes:Initializes a new NSAttributedString object by decoding the stream of RTFD commands and data contained in the given data object.
initWithRTFDFileWrapper:documentAttributes:Initializes a new NSAttributedString object from the given NSFileWrapper object containing an RTFD document.

In addition to these explicit RTF-reading methods, four methods implicitly allow loading RTF data from a file or URL-specified resource. NSAttributedString defines:

initWithPath:documentAttributes:Initializes a new NSAttributedString object from RTF or RTFD data contained in the file at the given path.
initWithURL:documentAttributes:Initializes a new NSAttributedString object from the data at the given URL.

NSMutableAttributedString defines:

readFromURL:options:documentAttributes:Sets the contents of receiver from the file at url.
readFromData:options:documentAttributes:Sets the contents of the receiver from the stream at data.

Handling Document Attributes

Attributed strings store attribute information for characters and paragraphs only, while RTF also supports more general attributes of a document, such as paper size and page layout. The Application Kit methods that work with RTF read and write some RTF directives for document attributes, stored in an NSDictionary object.

Many init methods return a dictionary containing the attributes read from RTF data, which you can use to set up a page layout. Similarly, RTF extraction methods such as RTFFromRange:documentAttributes:, accept a dictionary containing those attributes and write them into the RTF data, thus preserving the page layout information.

Table 1 lists the RTF document attributes supported by the Application Kit.

Table 1  Document attributes supported by RTF-handling methods

Attribute Key

Type

PaperSize

NSValue, containing NSSize

LeftMargin

NSNumber, containing a float, in points

RightMargin

NSNumber, containing a float, in points

TopMargin

NSNumber, containing a float, in points

BottomMargin

NSNumber, containing a float, in points

HyphenationFactor

NSNumber, containing a float

DocumentType

NSString; may be NSPlainTextDocumentType, NSRTFTextDocumentType, NSRTFDTextDocumentType, NSMacSimpleTextDocumentType, or NSHTMLTextDocumentType.

CharacterEncoding

NSNumber, containing an int specifying the NSStringEncoding used to interpret the file; for plain text files only.

ViewSize

NSValue, containing NSSize.

ViewZoom

NSValue, containing a float. 100 = 100% zoom.

ViewMode

NSValue, containing an int. 0 = normal; 1 = page layout (use value of PaperSize attribute).

CocoaRTFVersion

NSNumber, containing an int. If RTF file, stores the version of Cocoa with which the file was created. Absence of this value indicates RTF file not created by Cocoa or its predecessors. 0 = Not Cocoa writer, 1 = NextStep, 40 = OpenStep, 100 = Mac OS X 10.0, 102 = 10.2. (Other than incrementing the number for future versions, no assumptions should be made as to how the number will change in the future.)

Converted

NSNumber, containing an int. Indicates whether the file was converted by a filter service. If missing or zero, the file was originally in the format specified by document type. If 1 or more, it was converted to this type by a filter service. If negative, the file was converted “lossily,” meaning that some features of the original document were left out.

Handling Attachments

Attachments, such as embedded images or files, are represented in an attributed string by both a special character and an attribute. The character is identified by the global name NSAttachmentCharacter, and indicates the presence of an attachment at its location in the string. The attribute, identified in the string by the attribute name NSAttachmentAttributeName, is an NSTextAttachment object . An NSTextAttachment object contains the data for the attachment itself, as well as an image to display when the string is drawn.

You can use NSAttributedString’s attributedStringWithAttachment: class method to construct an attachment string, which you can then add to a mutable attributed string using appendAttributedString: or insertAttributedString:atIndex:. To write rich text data containing one or more attachments, use the RTFDFromRange:documentAttributes: method and the RTFDFileWrapperFromRange:documentAttributes: method. To initialize an attributed string with rich text data containing attachments, use the initWithRTFD:documentAttributes:, and initWithRTFDFileWrapper:documentAttributes: methods.

Apple’s RTF Extensions

Apple has extended the RTF language to support text attributes and formatting constructs available in the Cocoa text system but not representable with standard RTF. The Apple extensions take the same form as standard RTF commands, groups, and escapes. RTF commands consist of a backslash followed by a string of alphabetic characters (case sensitive) followed by an optional integer parameter value which can be positive or negative. RTF groups begin with a left brace ({), followed by RTF sequences optionally including other groups, closed by a right brace (}). RTF escapes consist of a backslash followed by a special character, such as \{, which indicates a literal left brace instead of the beginning of a group.

RTF includes the concept of a destination, which is a group containing an RTF command and text possibly to be inserted at a different location in a document, such as a footnote. The escape sequence \* indicates that RTF readers that don’t understand the command that follows should ignore the contents of the destination.

Dimensions in RTF are expressed in twips—one twip is one twentieth of a point.

Table 2 lists Apple’s RTF extensions for character attributes.

Table 2  Character attribute RTF extensions

RTF Sequence

Description

Parameter(s)

\CocoaLigatureN

Ligature control

Value of NSLigatureAttributeName.

0 = no ligatures, 1 = default ligatures, 2 = all ligatures. Default value 1.

\expansionN

Expansion factor to be applied to glyphs

2000 * value of NSExpansionAttributeName (log of expansion factor).

Default value 0.

\obliquenessN

Skew to be applied to glyphs

2000 * value of NSObliquenessAttributeName.

0 = no skew. Default value 0.

\fsmilliN

A finer specification for font size

1000 * font size.

Written in addition to \fs when \fs is not an integral or half-point value; value is overridden by \fs, so this should be written immediately after \fs. Default driven by \fs.

\shadxN \shadyN

Shadow offset, written in conjunction with \shad

X and Y offsets in twips (0 = no offset).

Defaults are \shadx3 and \shady-3.

\shadrN

Shadow blur, written in conjunction with \shad

Blur radius in twips.

0 = no blur. Default value 0.

\strikecN

Strikethrough color

Color number.

Default same as foreground text color.

\strikestyleN

Strikethrough style, written where \strike, \striked, \strikew are not sufficient

Style and pattern mask, value of NSObliquenessAttributeName.

0 = none; 0x8000 = by word; styles: 1 = single, 2 = thick, 9 = double; patterns: 0x100 = dotted, 0x200 = dash, 0x300 = dash dot, 0x400 = dash dot dot. Default value 0.

\strokecN

Stroke color

Color number.

Default same as foreground text color.

\strokewidthN

Glyph stroke width, written in conjunction with \outl.

20 * stroke width as percentage of font point size.

0 = no stroke. Default value 0. Negative values indicate that glyphs are both stroked and filled; the stroke width is taken from the absolute value of the parameter.

\ulstyleN

Underline style, written where the standard \ul commands are not sufficient

Style and pattern mask, value of NSUnderlineStyleAttributeName.

0 = none; 0x8000 = by word; styles: 1 = single, 2 = thick, 9 = double; patterns: 0x100 = dotted, 0x200 = dash, 0x300 = dash dot, 0x400 = dash dot dot. Default value 0.

{{\NeXTGraphic attachment \widthN \heightN} string}

Name of attachment file in the same folder as the RTF file (typically packaged within an RTFD document)

The attachment is the attachment file name, encoded in UTF-8 and properly RTF-escaped.

The width and height parameters optionally specify the attachment size in twips. The string is always 0xAC.

{{}{\*\glidN basestring}string}

Glyph ID for explicitly specified glyphs. (The extra {} pair is necessary to work around an RTF reader bug in Mac OS X version 10.2 and earlier.)

Glyph identifier (parameter to \glid). The basestring is the string the glyph id is intended to override; this attribute is then applied to the specified string. Typically string and basestring are the same, although string might contain multiple instances of basestring.

{{}{\*\glidN basestring\glcolN} string}

Glyph ID for explicitly specified glyphs

Character identifier (parameter to \glid) and character collection (parameter to \glcol).

Collection IDs: 0 = identity, 1 = Adobe-CNS1, 2 = Adobe-GB1, 3 = Adobe-Japan1, 4 = Adobe-Japan2, 5 = Adobe-Korea.

{{}{\*\glid basestring\glnam glyphname}string}

Glyph ID for explicitly specified glyphs

The glyphname is the glyph name in UTF-8 encoding.

\AppleTypeServicesUN

Character shape control

Value of NSCharacterShapeAttributeName.

The value is interpreted as Apple Type Services kCharacterShapeType selector + 1. The value 0 disables this attribute. Default value 0.

Table 3 lists Apple’s RTF extensions for paragraph attributes.

Table 3  Paragraph attribute RTF extensions

RTF Sequence

Description

Parameter(s)

\pardeftabN

Default tab interval for paragraph

Tab interval value in twips. 0 = no tabs other than those explicitly specified. Default value 0.

\qnatural

Natural text alignment for paragraph (based on script), written along with \ql

None

\slleadingN

Paragraph line spacing (NSParagraphStyle lineSpacing method)

Line spacing value in twips. Default value 0.

\slmaximumN

Maximum line height (NSParagraphStyle maximumLineHeight method), written along with \sl and if needed \slmult

Maximum line height value in twips. Default value 0, implying no maximum.

\slminimumN

Minimum line height (NSParagraphStyle minimumLineHeight method), written along with \sl and if needed \slmult

Minimum line height value in twips. Default value 0.

Table 4 lists Apple’s RTF extensions for document attributes.

Table 4  Document attribute RTF extensions

RTF Sequence

Description

Parameter(s)

\readonlydocN

Read-only document. This has nothing to do with the file system permissions or ownership of the file; it's just a hint that indicates that the document should be presented in a read-only fashion to the user, if the viewer or editor is capable.

0 = Not read-only, 1 = read-only. Default value 0.

\cocoartfN

Cocoa RTF-writer version number. This is a number used by Apple to indicate the version number of the RTF writer used to write this document.

Incrementing version number. 0 = Not Cocoa writer, 1 = NextStep, 40 = OpenStep, 100 = Mac OS X 10.0, 102 = 10.2. (Other than incrementing the number for future versions, no assumptions should be made as to how the number will change in the future.) Default value 0, although some heuristics are used to recognize pre–Mac OS X documents as such.

\viewhN \viewwN

Size of display area (not window or view size) to be used for displaying the document

Display area dimension in twips. Default value unspecified.



< Previous PageNext Page > Hide TOC


© 1997, 2007 Apple Inc. All Rights Reserved. (Last updated: 2007-06-04)


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.