Advanced API

Customizing text measure

SVG renderer needs to know dimensions of node’s text in order to size the diagram appropriately. By default, it uses a very crude heuristic of multiplying length of text by an average character width. If you have a font file, though, you can improve text measuring by providing an instance of TrueTextMeasure.

class syntax_diagrams.TextMeasure

An interface for measuring dimensions of rendered text.

abstract property ascent: float

Distance from the baseline to the highest outline point.

abstract property font_size: float

Font size.

abstract property line_height: float

Height of a single line, equals to CSS line-height property.

abstractmethod measure(text: str) Tuple[int, int]

Called before rendering a node to measure its text.

Should return a tuple (width, height).

class syntax_diagrams.SimpleTextMeasure(*, character_advance: float, wide_character_advance: float, font_size: float, line_height: float, ascent: float)

A simple text measuring service that multiplies length of the text by average width of the character. Works best for monospace fonts.

Parameters:
  • character_advance – average length of one character in the used font. Since SVG elements cannot expand and shrink dynamically, length of text nodes is calculated as number of symbols multiplied by this constant.

  • wide_character_advance – average length of one wide character in the used font.

  • font_size – font size.

  • line_height – height of a single line, equals to CSS line-height property.

  • ascent

    the distance from the baseline to the highest outline point.

    This is required because Chrome, Firefox and Safari all treat dominant-baseline attribute in a slightly different way.

class syntax_diagrams.TrueTextMeasure(font: FreeTypeFont | str | pathlib.Path, font_size: float, line_height: float)

A text measuring service that uses Python Image Library to calculate text’s actual size.

Parameters: