Skip to content
@deckyard/docs

RTF

readRtf reads a Rich Text Format file (.rtf, as Microsoft™ Word™, LibreOffice™ and older editors write it) into a Document; writeRtf writes one as RTF 1.9.1.

jennifer
import "@deckyard/docs/" as docs;
use fs;
use io;

def d as docs.Document init docs.readRtf(fs.readBytes("letter.rtf"));
io.printf("%s\n", docs.plainText($d));
fs.writeBytes("letter.docx", docs.writeDocx($d));
fs.writeBytes("copy.rtf", docs.writeRtf($d));

Reading

RTFDocument
\par, \pard, \sN, \qc \qr \qjparagraph; its role from the stylesheet (below), alignment as align
\b \i \ul \strike \super \sub \fN \fsN \cfN \highlightN \cbN, \plainRunStyle: what differs from the paragraph style's own formatting
a monospace font (\fmodern, \fprq1, or a known name)code; the font is named unless it is Courier New
\tab, \line, \page and \pagebbtab, line break, a "pagebreak" block
\emdash \endash \bullet \lquote \rquote \ldblquote \rdblquote \enspace \emspace, \~, \_their characters; \- is dropped
\uN (with \ucN fallback skipping), \'hh, 8-bit texttext; see code pages below
\listtable, \listoverridetable, \lsN \ilvlNlistId and listLevel; one ListDef per override, in table order, from its level 0
{\*\pn ...} (old-style numbering)a list per run of paragraphs with the same format and start
\trowd \cellxN \intbl \cell \rowtable; \clmgf/\clmrg and wider \cellx edges as colspan, \clvmgf/\clvmrg as rowspan with the covered cells left out, leading \trhdr rows as headerRows
\itapN \nestcell \nestrow, \nesttablepropstables in cells
HYPERLINK fieldlink on the field result; \l gives #anchor
any other fieldits result text
\footnote"note" inline and a Note (endnotes too)
\annotation with \atnauthor, \atnid, \atndate"comment" inline and a Comment
\pict with \pngblip / \jpegblip (hex or \bin)"image" inline and a Media; size from \picwgoal/\pichgoal and the scale, alt text from wzDescription
\shppict / \nonshppictthe first; the fallback is skipped
\header, \headerr, \footer, \footerrheader / footer, the first of each
\deleted, \revisedchange "delete" / "insert"
\vhidden text, dropped
\infometa: title, subject, author, keywords, doccomm, \creatim, \revtim
\paperw \paperh \margl \margr \margt \margb (and the sxn forms)page; without them US Letter with RTF's default margins

Unknown control words are ignored and unknown {\*...} destinations are skipped, as the format requires. Left out on purpose: first-page and left-page headers and footers, \listtext and \pntext (the rendered numbers), index and table-of-contents entries, bookmarks, shapes and text boxes, sections (\sect only ends a paragraph).

Paragraph roles

Style name (any case)Role
heading 1 to heading 9 (7 to 9 as 6)"heading", its level
any other with \outlinelevelN"heading", level N + 1
Title, Subtitle"title", "subtitle"
Quote, Quotations, Intense Quote, Block Text"quote"
caption"caption"
Source Code, Preformatted Text, HTML Preformatted, or a monospace font"code"
Term, Definition Term, List Heading / Definition, List Contents"term" / "definition"
Horizontal Rule, Horizontal Line"rule"

Code pages

\'hh and 8-bit bytes are decoded through the code page of the current font's \fcharsetN (or \cpgN), else the document's (\ansicpgN, \mac).

SupportedRefused, kind "docs"
1250 to 1258, Mac Roman (\mac, \fcharset77), 20127 (ASCII), 28591 (Latin-1)874, 932, 936, 949, 950, 1361, 437 (\pc), 850 (\pca), any other

A refusal happens only when a byte above 0x7F has to be decoded. Word writes East Asian text as \uN with the code page bytes as the skipped fallback, so such a file reads. A byte a code page leaves undefined (0x81 in 1252) is refused too. A font name that cannot be decoded is dropped.

Limits and refusals

InputError
not starting with {\rtf1, unbalanced braces, content after the last }"docs"
a control word over 32 letters, a parameter over 10 digits, \' without two hex digits, \bin past the end"docs"
an unpaired UTF-16 surrogate in \uN, \uN outside -32768 to 65535, a negative \ucN"docs"
picture data that is not hex, or not the PNG or JPEG it claims"docs"
groups nested deeper than MAX_NESTING (100); more than MAX_BLOCKS blocks, MAX_CELLS cells or MAX_TEXT characters in the document; more than MAX_INLINES inlines in a paragraph; a span past MAX_SPAN; more than 4 Mi tokens or 256 MiB of input"limit"

Pictures in formats the model cannot hold (WMF, EMF, PICT, DIB) are not malformed input: they are left out.

\ucN skipping follows RTF 1.9.1: after \uN the next N characters are skipped, a control word or symbol, a \'hh or \bin data counting as one character, and a brace ends the skip. Normalised rather than refused, so the document passes checkDocument: a font size is clamped to 2 to 3276 half-points; a page side of 0 or less is ignored and a larger one cut to 288,000 twips; negative margins become positive and margins that fill the page are narrowed; a date out of range reads as ""; a note inside a note becomes text; a picture size out of range falls back to the picture's own; " is dropped from a bookmark name; U+FFFE, U+FFFF and control characters other than tab, line feed and carriage return are dropped.

Writing

The file is 7-bit ASCII: {, } and \ are escaped, every other character is \uN? under \uc1 (N negative above 32767, a surrogate pair above U+FFFF). The same document always gives the same bytes.

DocumentRTF
rolesa stylesheet Word maps: heading 1 to heading 6 (with \outlinelevel), Title, Subtitle, Quote, Source Code, caption, Term, Definition, Horizontal Rule (a bottom border); each paragraph repeats its style's formatting
RunStylea group per formatted run; fonts and colours collected into \fonttbl (Calibri body, Courier New code) and \colortbl; highlight as yellow
listsone \list of nine levels per ListDef (\levelnfc 0, 1, 2, 3, 4 or 23, \levelstartat), list i as \ls i
tables\trowd rows, one cell per grid column: \clmgf/\clmrg for a column span, \clvmgf/\clvmrg for a row span, \trhdr header rows; tables in cells with \itapN, \nestcell and \nesttableprops
linksHYPERLINK fields; #name as \l "name"
notes\footnote at the reference, so an unreferenced note is not written
pictures\pict\pngblip or \jpegblip in hex, \picwgoal from the display size, alt text as wzDescription
header, footer, meta, page\header, \footer, \info (dates as \creatim/\revtim, the zone dropped), \paperw and margins

Refused with kind "docs", as writeDocx refuses them: an unknown role, heading level, alignment or inline kind, a list, note or picture that does not exist, a span below 1, a colour that is not six hex digits, a control character, plus what RTF cannot hold: a GIF picture, a footnote inside a footnote, a font name with ;, a date that is not ISO 8601. Comments and the document language are not written.

Round trips

readRtf(writeRtf($d)) gives back the same blocks, lists, notes, pictures, header, footer, properties and page, with these differences:

WrittenRead back
a date with a zone or fractional secondslocal time, YYYY-MM-DDTHH:MM:SS
a run in a monospace font without codecode set, the font kept
text holding a tab or line endseparate "tab" / "break" inlines
a cell ending in a tablean empty paragraph after it
media no inline refers todropped; pictures are named image1.png, image2.jpg, ...
language, commentslost
neighbouring text inlines of the same formattingone inline
an empty cella cell holding one empty paragraph
" in a link target%22