Skip to content

About

A comprehensive JavaScript library for creating Rich Text Format (RTF/DOCX) documents.

Resources

Stars

3 stars

Watchers

0 watching

Forks

Repository files navigation

RTF Builder

npm

A modern JavaScript library for creating Rich Text Format (RTF/DOCX) documents using an intuitive builder pattern.

Introduction

This project germinated due to a lack of library options with typescript support to generate RTF/DOCX documents directly from a web browser. The goal is to be able to export a simple document - think markdown or similar - to an office compatible format with a bit of control on the styling.

Here is a list of supported features:

  • Document structure: sections with header/footer, tables, lists, paragraphs.
  • Navigation: bookmarks, hyperlinks, footnotes.
  • Basic picture support.

The library is built around a document builder using fluent patterns to programmatically compose the document, a document model to represent the document state and a renderer to output into the target format. There's also a validator which can check that the document instance is well-formed (optional).

Roadmap

The library seems stable enough for some serious usage at this point. Ensuring the library is bug-free is a priority.

Then, there is plenty of room for improvements and additional features; contributions are welcome.

  • Battle testing the document builder interface and ironing out discrepancies (~v0.9)
  • Refining the renderer to have maximum compatibility with popular text editors (~v1.0)
  • A module to convert a simple HTML document to RTF (ideal for rendered markdown)
  • A renderer for OOXML (but only for cross-compatible features with RTF)
  • Implementation of additional RTF constructs
    • comments
    • custom tab markers
    • picture/shape with text flow
    • positioned frame

Alternatives

You may be interested in other projects that I stumbled upon:

Installation

yarn add rtfbuilder

Quick Start

import { RichTextDocumentBuilder, pt } from "rtfbuilder";
import { RTFDocument } from "rtfbuilder/rtf";

// Create a document builder
const builder = new RichTextDocumentBuilder();

// Add colors and fonts
builder.withColor("red", { red: 255, green: 0, blue: 0 });

// Create content
builder.withSection((section) => {
  // Add a title
  section.body.withTitle("My Document");

  // Add a paragraph with mixed formatting
  section.body.withText("Here is some ", { bold: true, colorAlias: "red" }, "bold red text", {}, " and some regular text.");

  // Add a simple table
  section.body.withSimpleTable(["Header 1", "Header 2"], [["Row 1 Col 1", "Row 1 Col 2"]]);
});

// Generate RTF content (into a string)
console.log(builder.buildInto(new RTFDocument()).render());

To output to DOCX (ECMA-376), replace the last line by:

import { OOXMLDocument } from "rtfbuilder/ooxml";

const zipData = builder.buildInto(new OOXMLDocument()).render();

API Reference

Document Builder

The RichTextDocumentBuilder class provides the main entry point for creating RTF documents:

const builder = new RichTextDocumentBuilder();

// Document metadata
builder.info({ title: "My Document", author: "John Doe" });
builder.withProperty("Client", "ACME").withProperty("Due", new Date()); // custom properties (text, number, boolean, date)
builder.withVariable("project", "Apollo"); // document variables, shown by { special: "docVariable", name: "project" }

// Page setup
builder.pageSetup({
  paperWidth: mm(210), // A4 width
  paperHeight: mm(297), // A4 height
  margin: { top: mm(20), right: mm(20), bottom: mm(20), left: mm(20) },
});

// Add resources
builder.withColor("blue", { red: 0, green: 0, blue: 255 });
builder.withFont("times", { name: "Times New Roman", family: "roman" });

Text Formatting

Add formatted text using the fluent API:

section.body.withText(
  "Normal text ",
  { bold: true },
  "bold text ",
  {},
  ", normal again, ",
  { underline: true, fontAlias: "times", fontSize: pt(14) },
  "large underlined text",
);

// background color (any registered color) vs highlighter (one of Word's 16 highlight colors)
section.body.withText({ highlightColorAlias: "lightBlue" }, "shaded", {}, " and ", { highlight: "yellow" }, "highlighted");
// effects and baseline offset
section.body.withText({ flags: ["outline", "shadow"] }, "outlined", { flags: ["emboss"] }, "embossed", { position: pt(3) }, "raised");

Headings

Headings use Word's built-in styles (Title, heading 1 to heading 9), so the navigation pane, the PDF bookmarks and a table of contents find them. Each style is registered on first use, unless you defined a style with the same alias first:

section.body.withTitle("Report"); // style "Title"
section.body.withHeading("Introduction", 1, "intro"); // style "heading 1" (outline level 0), with a bookmark

// your own look for level 2 (keep the outline level)
builder.withStyle("heading 2", {
  type: "paragraph",
  paragraphFormatting: { outlineLevel: 1, spaceBefore: pt(12), flags: ["keepNext"] },
  characterFormatting: { fontSize: pt(14), italic: true },
});

// any paragraph can have an outline level 0-8
section.body.withParagraph((p) => p.outlineLevel(2).withText("Appears in the navigation pane"));

Tables

Create tables with rich formatting:

section.body.withTable((table) => {
  // Table-level formatting
  table.cellBorder("all", { width: pt(1), colorAlias: "black" });
  table.cellPadding({ top: pt(5), right: pt(5), bottom: pt(5), left: pt(5) });

  // Header row
  table.withHeaderRow((row) => {
    row.newCell().withText({ bold: true }, "Header 1");
    // or:
    row.withCell((cell) => cell.withText({ bold: true }, "Header 2"));
  });

  // Data rows
  table.withRow((row) => {
    row.newCell().withText("Data 1");
    row.withCell((cell) => {
      cell.backgroundColor("lightGray"); // registered with builder.withColor("lightGray", { red: 211, green: 211, blue: 211 })
      cell.withText("Shaded cell");
    });
  });
});

Cells can contain nested tables, as wide as the cell: cell.withTable((nested) => nested.withRow(...)).

Columns have fixed widths by default; table.layout("auto") lets readers fit them to the content, with cell widths as preferences: cell.width(pt(60)). Cells can also have vertical text: cell.textDirection("btlr") (or "tbrl").

Lists

Create bulleted or numbered lists:

section.body.withList((list) => {
  list.simple("bullet"); // or "decimal", "lowerRoman", "upperRoman", "lowerLetter", "upperLetter", "none"

  list.withItem((item) => item.withText("First item"));
  list.withItem((item) => {
    item.withText("Second item with nested list");
    item.withItem((nested) => nested.withText("Nested item"));
  });
});

// legal numbering (%1-%9 are the numbers of levels 1-9) and custom bullets
section.body.withList((list) => {
  list.levels({ format: "decimal" }, { format: "decimal", text: "%1.%2." }, { format: "bullet", bullet: { char: "\u2013" } });
  list.withItem((item) => item.withText("1.").withItem((nested) => nested.withText("1.1.")));
});

Advanced Features

Pictures and captions

Pictures can be png, jpeg, emf or wmf; gif and svg pictures need a png or jpeg fallback (rtf has no gif or svg pictures, and readers without svg show the fallback):

section.body.withPicture({ format: "svg", data: svgBytes, width: 100, height: 100, fallback: pngPicture }, { displayWidth: inch(1) });
// alternative text and title for accessibility, then a numbered caption ("Figure 1: ...")
section.body.withPicture(pictureData, { displayWidth: inch(2), altText: "Sales by month", title: "Chart" }).closeParagraph();
section.body.withCaption("Figure", "Sales by month", { bookmark: "chart" });

// floating picture, with the text wrapping around it (wrap: "square", "topAndBottom", "none" or "behind")
section.body.withPicture(pictureData, { displayWidth: inch(1), float: { align: "right", wrap: "square", distance: pt(6) } }); // { special: "ref", bookmark: "chart" } shows "Figure 1"

section.body.withTable((table) => {
  table.caption("Sales").description("Sales by month"); // for accessibility (not displayed)
  table.withCaptionParagraph("Sales by month"); // visible "Table 1: ..." above the table (position: "below" for below)
  table.withRow((row) => row.newCell().withText("..."));
});

Footnotes and Endnotes

section.body.withFootnote("Text with footnote", "This is a footnote");

// notes of several paragraphs
section.body.withParagraph((p) =>
  p.withChunk((c) =>
    c.text("Text").withFootnote((f) => {
      f.withText("First paragraph of the note.");
      f.withParagraph((np) => np.withText("Second paragraph."));
    }),
  ),
);

Hyperlinks and bookmarks

section.body.withTitle("Example", "section1");
section.body.withBookmarkLink("section1", "Go to Section 1").closeParagraph();
section.body.withExternalLink("https://example.com", "Visit Example").closeParagraph();

Languages and right-to-left text

builder.language("fr-CH", { eastAsia: "ja-JP", complex: "ar-SA" }); // default languages (BCP-47 tags)

section.body.withText({ language: "de-DE" }, "Deutsch"); // or a Windows LCID: { language: 1031 }
section.body.withParagraph((p) => p.rtl().withText({ rtl: true, complexFontAlias: "arabic" }, "مرحبا")); // right-to-left
section.body.withText({ eastAsianFontAlias: "mincho", eastAsianLanguage: "ja-JP" }, "日本語");

In right-to-left paragraphs, left() and right() align to the start and the end of the line.

Fields and table of contents

// table of contents of the headings 1-3, linked to them (Word asks to update its page numbers when the document opens)
section.body.withTableOfContents({ title: "Contents", levels: [1, 3] });

section.body.withHeading("Introduction", 1, "intro");
section.body.withText(
  "Figure ",
  { special: "seq", name: "Figure" }, // numbered captions: 1, 2, 3... (format: "upperRoman"...)
  ": see ",
  { special: "ref", bookmark: "intro" }, // text of a bookmark
  " on page ",
  { special: "pageRef", bookmark: "intro" }, // page of a bookmark
  " for ",
  { special: "docVariable", name: "client" }, // builder.withVariable("client", "ACME")
  { field: "AUTHOR", result: "me" } // any field code, with its cached result
);
section.footer.withText("Page ", { special: "pageNumber" }, " of ", { special: "sectionPages" });

Section layout

builder.withSection((section) => {
  section.columns([inch(2), inch(4)], pt(18)).lineBetweenColumns(); // or columns(2) for equal columns
  section.lineNumbering({ countBy: 5, distance: pt(12), restart: "page" }); // or "section", "continuous"
  section.pageBorder("all", { style: "double", width: pt(1), spacing: pt(12) }, "text"); // spacing from the text
});

Headers and Footers

section.header.withParagraph((p) => {
  p.center();
  p.withText("Document Header");
});
section.footer.withParagraph((p) => {
  p.withText({ fontSize: pt(10) }, "Page ", { special: "pageNumber" });
});

Tab stops

A paragraph can be placed in a positioned frame, with the text wrapping around it (consecutive paragraphs with the same frame share it):

section.body.withParagraph((p) =>
  p.frame({ width: inch(2), x: "right", horizontalAnchor: "margin", y: pt(6), wrap: "around", distance: pt(9) }).withText("Sidebar"),
);

Custom tab stops align text at fixed positions, e.g. a footer with left, centered and right parts:

section.footer.withParagraph((p) => {
  p.tabStop(section.computedContentWidth / 2, { align: "center" });
  p.tabStop(section.computedContentWidth, { align: "right", leader: "dot" }); // also "decimal"; leaders "hyphen", "underscore"...
  p.withText("Report", { special: "tab" }, "Draft", { special: "tab" }, "Page ", { special: "pageNumber" });
});

Size Units

The library provides utilities for different measurement units:

import { pt, mm, cm, inch } from "rtfbuilder";

// Point sizes (1/72 inch)
fontSize: pt(12);

// Millimeters
margin: {
  top: mm(25);
}

// Centimeters
width: cm(5);

// Inches
pageWidth: inch(8.5);

Validation

Enable optional document validation during development:

import { RTF_DOCUMENT_VALIDATOR } from "rtfbuilder/validation";

const doc = new RTFDocument({ validator: RTF_DOCUMENT_VALIDATOR });
const content = builder.buildInto(doc).render();

Examples

See the demo folder for complete examples including:

If you are flakes-ready, the dev shell contains a run-demos script to generate the corresponding RTF/DOCX. Otherwise:

run-demos
# or
run-demo simple
# or
tsx demo/cli.ts --validate simple simple.docx
tsx demo/cli.ts --validate simple simple.rtf

OOXML validation

The dev shell contains a script to validate an OOXML/DOCX against the ECMA-376 XSDs:

validate-ooxml simple.docx

License

MIT

About

A comprehensive JavaScript library for creating Rich Text Format (RTF/DOCX) documents.

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages