Skip to content

RTFDocument

Main entry point for creating complete RTF documents using the unified encoding pipeline. Use this class to combine pages, headers/footers, titles, tables, and figures into production-ready 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 Sequence[RTFColumnHeader] | Sequence[Sequence[RTFColumnHeader | None]]

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

rtf_body RTFBody | Sequence[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 column references and multi-section consistency.

validate_dataframe(values) classmethod

Convert DataFrame(s) to polars for internal processing.

write_docx(file_path, *, converter=None)

Write the document as a DOCX file.

Writes the document to a temporary RTF file first, and then converts it to DOCX with LibreOffice. Temporary directories are used for all intermediate files to avoid placing artifacts alongside the requested output path.

Parameters:

Name Type Description Default
file_path str | Path

Destination path for the DOCX file. Accepts string or Path input. Can be absolute or relative. Directories are created if they do not already exist.

required
converter LibreOfficeConverter | None

Optional LibreOffice converter instance. Pass a configured instance (for example with a custom executable_path) to control how LibreOffice is invoked and to avoid re-initializing and re-verifying the executable path across multiple conversions. Note that each call to convert() still starts a new LibreOffice process in headless mode; the process is not kept alive between conversions.

None

Examples:

doc = RTFDocument(df=data, rtf_title=RTFTitle(text="Report"))
doc.write_docx("output/report.docx")

Custom LibreOffice executable:

converter = LibreOfficeConverter(executable_path="/custom/path/to/soffice")
doc.write_docx("output/report.docx", converter=converter)

Note

The method prints the file path to stdout for confirmation.

write_html(file_path, *, converter=None)

Write the document as an HTML file.

Writes the document to a temporary RTF file first, and then converts it to HTML with LibreOffice. Temporary directories are used for all intermediate files to avoid placing artifacts alongside the requested output path.

Parameters:

Name Type Description Default
file_path str | Path

Destination path for the HTML file. Accepts string or Path input. Can be absolute or relative. Directories are created if they do not already exist.

required
converter LibreOfficeConverter | None

Optional LibreOffice converter instance. Pass a configured instance (for example with a custom executable_path) to control how LibreOffice is invoked and to avoid re-initializing and re-verifying the executable path across multiple conversions. Note that each call to convert() still starts a new LibreOffice process in headless mode; the process is not kept alive between conversions.

None

Examples:

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

LibreOffice may create a companion directory (for example report.html_files) for embedded resources. When present, it is moved alongside the requested output path.

write_pdf(file_path, *, converter=None)

Write the document as a PDF file.

Writes the document to a temporary RTF file first, and then converts it to PDF with LibreOffice. Temporary directories are used for all intermediate files to avoid placing artifacts alongside the requested output path.

Parameters:

Name Type Description Default
file_path str | Path

Destination path for the PDF file. Accepts string or Path input. Can be absolute or relative. Directories are created if they do not already exist.

required
converter LibreOfficeConverter | None

Optional LibreOffice converter instance. Pass a configured instance (for example with a custom executable_path) to control how LibreOffice is invoked and to avoid re-initializing and re-verifying the executable path across multiple conversions. Note that each call to convert() still starts a new LibreOffice process in headless mode; the process is not kept alive between conversions.

None

Examples:

doc = RTFDocument(df=data, rtf_title=RTFTitle(text="Report"))
doc.write_pdf("output/report.pdf")

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

Path where the RTF file should be saved. Accepts string or Path input. Can be absolute or relative. Directories are created if they do not already 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.