CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-docxtpl

Use a docx as a jinja2 template

Pending
Overview
Eval results
Files

rich-text.mddocs/

Rich Text Formatting

Advanced text formatting capabilities for creating rich content within templates. DocxTpl provides classes for styled text, hyperlinks, and complex paragraph formatting that preserve Word document styling while enabling programmatic content generation.

Capabilities

RichText Class

Class for generating formatted rich text within existing paragraphs. Allows complex formatting combinations including fonts, colors, styles, and hyperlinks.

class RichText:
    def __init__(self, text=None, **text_prop):
        """
        Initialize RichText with optional initial text and formatting properties.
        
        Parameters:
        - text: Initial text content
        - **text_prop: Initial formatting properties (style, color, bold, etc.)
        """

Rich Text Content Addition

Add formatted text segments to build complex rich text elements.

def add(self, text, style=None, color=None, highlight=None, size=None, 
        subscript=None, superscript=None, bold=False, italic=False, 
        underline=False, strike=False, font=None, url_id=None, 
        rtl=False, lang=None):
    """
    Add formatted text segment to the rich text element.
    
    Parameters:
    - text: Text content to add
    - style: Word style name to apply
    - color: Text color (RGB hex string like 'FF0000' or color name)
    - highlight: Highlight color for text background
    - size: Font size in points
    - subscript: Enable subscript formatting (bool)
    - superscript: Enable superscript formatting (bool)
    - bold: Enable bold formatting (bool)
    - italic: Enable italic formatting (bool)
    - underline: Enable underline formatting (bool)
    - strike: Enable strikethrough formatting (bool)
    - font: Font family name
    - url_id: URL ID for hyperlink (use DocxTemplate.build_url_id())
    - rtl: Right-to-left text direction (bool)
    - lang: Language code for text
    """

RichText String Methods

Methods for converting rich text to XML representation for template insertion.

def __str__(self) -> str:
    """Return XML representation of rich text."""

def __unicode__(self) -> str:
    """Return Unicode XML representation of rich text."""

def __html__(self) -> str:
    """Return HTML-like representation of rich text."""

RichTextParagraph Class

Class for generating rich text paragraphs outside existing paragraphs. Creates standalone paragraph elements with rich formatting.

class RichTextParagraph:
    def __init__(self, text=None, **text_prop):
        """
        Initialize RichTextParagraph with optional initial text and properties.
        
        Parameters:
        - text: Initial text content
        - **text_prop: Initial formatting properties
        """

Rich Paragraph Content Addition

Add paragraph content with specific paragraph-level styling.

def add(self, text, parastyle=None):
    """
    Add paragraph with formatting.
    
    Parameters:
    - text: Paragraph text content
    - parastyle: Word paragraph style name to apply
    """

RichTextParagraph String Methods

Methods for converting rich text paragraphs to XML representation.

def __str__(self) -> str:
    """Return XML representation of rich text paragraph."""

def __unicode__(self) -> str:
    """Return Unicode XML representation of rich text paragraph."""

def __html__(self) -> str:
    """Return HTML-like representation of rich text paragraph."""

Type Aliases

Convenient aliases for rich text classes.

R = RichText         # Alias for RichText class
RP = RichTextParagraph  # Alias for RichTextParagraph class

Usage Examples

Basic Rich Text Formatting

from docxtpl import DocxTemplate, RichText

doc = DocxTemplate("template.docx")

# Create rich text with multiple formats
rt = RichText()
rt.add("Hello ", bold=True, color="FF0000")
rt.add("World", italic=True, color="0000FF", underline=True)
rt.add("!", size=16, font="Arial")

context = {
    'greeting': rt
}

doc.render(context)
doc.save("formatted_output.docx")

Advanced Text Formatting

from docxtpl import DocxTemplate, RichText, R

doc = DocxTemplate("report_template.docx")

# Using alias and advanced formatting
title = R("IMPORTANT NOTICE", bold=True, size=14, color="FF0000", highlight="FFFF00")

# Build formatted content with hyperlinks
url_id = doc.build_url_id("https://example.com")
content = R()
content.add("Visit our website ", color="000000")
content.add("here", color="0000FF", underline=True, url_id=url_id)
content.add(" for more information.", color="000000")

context = {
    'notice_title': title,
    'website_link': content
}

doc.render(context)
doc.save("notice.docx")

Rich Text Paragraphs

from docxtpl import DocxTemplate, RichTextParagraph, RP

doc = DocxTemplate("document_template.docx")

# Create formatted paragraphs
header = RP("Executive Summary", parastyle="Heading 1")
intro = RP("This document provides an overview of our quarterly results.", parastyle="Normal")

# Multi-format paragraph
conclusion = RP()
conclusion.add("In conclusion, ", bold=False)
conclusion.add("performance exceeded expectations", bold=True, color="008000")
conclusion.add(" in all key metrics.", bold=False)

context = {
    'header': header,
    'introduction': intro,
    'conclusion': conclusion
}

doc.render(context)
doc.save("executive_summary.docx")

Scientific Text with Subscripts and Superscripts

from docxtpl import DocxTemplate, RichText

doc = DocxTemplate("scientific_template.docx")

# Chemical formula
formula = RichText()
formula.add("H", color="000000")
formula.add("2", subscript=True, color="000000")
formula.add("SO", color="000000")
formula.add("4", subscript=True, color="000000")

# Mathematical expression
math_expr = RichText()
math_expr.add("E = mc", color="000000")
math_expr.add("2", superscript=True, color="000000")

context = {
    'chemical_formula': formula,
    'einstein_equation': math_expr
}

doc.render(context)
doc.save("scientific_document.docx")

Multi-language Support

from docxtpl import DocxTemplate, RichText

doc = DocxTemplate("multilingual_template.docx")

# Right-to-left text support
arabic_text = RichText("مرحبا بالعالم", rtl=True, lang="ar-SA", font="Arial Unicode MS")

# Mixed language content
mixed = RichText()
mixed.add("English text ", lang="en-US")
mixed.add("中文文本", lang="zh-CN", font="SimSun")
mixed.add(" français", lang="fr-FR")

context = {
    'arabic_greeting': arabic_text,
    'multilingual_text': mixed
}

doc.render(context)
doc.save("multilingual_document.docx")

Install with Tessl CLI

npx tessl i tessl/pypi-docxtpl

docs

index.md

media-composition.md

rich-text.md

template-processing.md

tile.json