Skip to content

RTFDocument

The RTFDocument class is the main entry point for creating RTF documents with rtflite. It orchestrates all components to generate properly formatted RTF output.

Bases: BaseModel

Main class for creating RTF documents with tables, text, and figures.

RTFDocument is the central class for generating Rich Text Format (RTF) files containing formatted tables, titles, footnotes, and other document elements. It provides a comprehensive API for creating professional documents commonly used in clinical trials, scientific research, and data reporting.

Examples:

Simple table with title:

import rtflite as rtf
import polars as pl

df = pl.DataFrame({
    "Subject": ["001", "002", "003"],
    "Age": [45, 52, 38],
    "Treatment": ["Drug A", "Drug B", "Placebo"]
})

doc = rtf.RTFDocument(
    df=df,
    rtf_title=rtf.RTFTitle(text="Patient Demographics"),
    rtf_body=rtf.RTFBody(col_rel_width=[2, 1, 2])
)
doc.write_rtf("demographics.rtf")

Multi-page document with headers and footers:

doc = rtf.RTFDocument(
    df=large_df,
    rtf_page=rtf.RTFPage(nrow=40, orientation="landscape"),
    rtf_page_header=rtf.RTFPageHeader(),  # Default page numbering
    rtf_page_footer=rtf.RTFPageFooter(text="Confidential"),
    rtf_title=rtf.RTFTitle(text="Clinical Study Results"),
    rtf_column_header=rtf.RTFColumnHeader(
        text=["Subject ID", "Visit", "Result", "Units"]
    ),
    rtf_body=rtf.RTFBody(
        col_rel_width=[2, 1, 1, 1],
        text_justification=[["l", "c", "r", "c"]]
    ),
    rtf_footnote=rtf.RTFFootnote(
        text="Results are mean +/- SD"
    )
)
doc.write_rtf("results.rtf")

Document with grouped data and sublines:

doc = rtf.RTFDocument(
    df=grouped_df,
    rtf_body=rtf.RTFBody(
        group_by=["SITE", "TREATMENT"],  # Suppress duplicate values
        subline_by=["STUDY_PHASE"],      # Create section headers
        col_rel_width=[2, 2, 1, 1]
    )
)

Attributes:

Name Type Description
df DataFrame | list[DataFrame] | None

Data to display in the table. Can be a single DataFrame or list of DataFrames for multi-section documents. Accepts pandas or polars DataFrames (automatically converted to polars internally).

rtf_page RTFPage

Page configuration including size, orientation, margins, and pagination settings.

rtf_page_header RTFPageHeader | None

Optional header appearing at the top of every page.

rtf_page_footer RTFPageFooter | None

Optional footer appearing at the bottom of every page.

rtf_title RTFTitle | None

Document title(s) displayed at the top.

rtf_column_header list[RTFColumnHeader] | list[list[RTFColumnHeader | None]]

Column headers for the table. Can be a single header or list of headers for multi-row headers.

rtf_body RTFBody | list[RTFBody] | None

Table body configuration including column widths, formatting, borders, and special features like group_by and subline_by.

rtf_footnote RTFFootnote | None

Optional footnote text displayed after the table.

rtf_source RTFSource | None

Optional source citation displayed at the very bottom.

rtf_figure RTFFigure | None

Optional figure/image to embed in the document.

Methods:

Name Description
rtf_encode

Generate the complete RTF document as a string.

write_rtf

Write the RTF document to a file.

convert_column_header_to_list(v)

Convert single RTFColumnHeader to list or handle nested list format

rtf_encode()

Generate the complete RTF document as a string.

This method processes all document components and generates the final RTF code including headers, formatting, tables, and all other elements. The resulting string can be written to a file or processed further.

Returns:

Name Type Description
str str

Complete RTF document string ready to be saved as an .rtf file.

Examples:

doc = RTFDocument(df=data, rtf_title=RTFTitle(text="Report"))
rtf_string = doc.rtf_encode()
# Can write manually or process further
with open("output.rtf", "w") as f:
    f.write(rtf_string)

validate_column_names()

Validate that column references exist in DataFrame and multi-section consistency.

validate_dataframe(values) classmethod

Convert DataFrame(s) to polars for internal processing.

write_rtf(file_path)

Write the RTF document to a file.

Generates the complete RTF document and writes it to the specified file path. The file is written in UTF-8 encoding and will have the .rtf extension.

Parameters:

Name Type Description Default
file_path str

Path where the RTF file should be saved. Can be absolute or relative path. Directory must exist.

required

Examples:

doc = RTFDocument(df=data, rtf_title=RTFTitle(text="Report"))
doc.write_rtf("output/report.rtf")
Note

The method prints the file path to stdout for confirmation. Ensure the directory exists before calling this method.