Skip to main content

Customize a new renderer

This section introduces code-controlled customizations of the rendering.

1. Customize tags by configurations​

BBCodeRenderer accepts an optional configuration object BBCodeConfig. This configuration object allows users to override default tag names.

config = stet.BBCodeConfig(h1="h2", h2="h3", h3="b", h4="u", h5="i", h6="i")
fobj.write(stet.BBCodeRenderer(config).render(doc))

This customization will lower down the level of titles.

example.md
# Main title

## Secondary title

### Subsection title

#### Subsubsection title

##### Paragraph title

content.

2. Customize rendering by subclassing​

By subclassing BBCodeRenderer, users can control the rendering in the fine-grained level.

The following example will override the default behavior when rendering h1 titles. It will capture the title text and save it as a figure. In the rendered BBCode file, the title will be replaced with a "placeholder" specifying the figure name.

customization.py
import os
import steam_editor_tools as stet


class H1TitleRenderer(stet.BBCodeRenderer):
"""Will Produce a figure of each H1 title during the rendering."""

def __init__(self, configs: stet.BBCodeConfig | None = None) -> None:
super().__init__(configs)
self._name_count = 0
self._h1_dir = os.path.join(".", "out-figs")

# Search the font to be used.
# May need to run `apt install fonts-open-sans`.
font = stet.FontLocator().query_best("OpenSans-Bold")
assert font is not None
self.font = font
os.makedirs(self._h1_dir, exist_ok=True)

def draw_h1_title(self, text: str) -> int:
"""Draw and save the H1 title image."""
count = self._name_count + 1
stet.ImageMultiLayer(width=1680, height=240).add_background().add_text(
text,
name="text",
font=self.font,
font_size="h1",
color="white",
stroke_color="cyan",
shadow_color="black",
).save(
os.path.join(self._h1_dir, "h1-{0:03d}.png".format(count)), quality="medium"
)
self._name_count = count
return count

def render_heading(self, node: stet.bbcode.nodes.HeadingNode) -> str:
# Catch the level 1 title.
if node.level == 1:
count = self.draw_h1_title(node.pure_text)
return "[FIGURE_h1_{0:03d}]\n\n".format(count)

return super().render_heading(node)


def convert(file_path: str) -> None:
out_file_path = os.path.splitext(file_path)[0].strip() + ".bbcode"
doc = stet.DocumentParser().parse_file(file_path)
with open(out_file_path, "w", encoding="utf-8") as fobj:
fobj.write(H1TitleRenderer().render(doc))


convert("example.md")
example.md
# Main title

## Secondary title

# Another H1 title

## More secondary title

...