Text Tools

MTextEditor

class ezdxf.tools.text.MTextEditor(text: str = '')

The MTextEditor is a helper class to build MTEXT content strings with support for inline codes to change color, font or paragraph properties. The result is always accessible by the text attribute or the magic __str__() function as str(MTextEditor("text")).

All text building methods return self to implement a floating interface:

e = MTextEditor("This example ").color("red").append("switches color to red.")
mtext = msp.add_mtext(str(e))

The initial text height, color, text style and so on is determined by the DXF attributes of the MText entity.

Warning

The MTextEditor assembles just the inline code, which has to be parsed and rendered by the target CAD application, ezdxf has no influence to that result.

Keep inline formatting as simple as possible, don’t test the limits of its capabilities, this will not work across different CAD applications and keep the formatting in a logic manner like, do not change paragraph properties in the middle of a paragraph.

There is no official documentation for the inline codes!

Parameters:

text – init value of the MTEXT content string.

text

The MTEXT content as a simple string.

append(text: str) MTextEditor

Append text.

__iadd__(text: str) MTextEditor

Append text:

e = MTextEditor("First paragraph.\P")
e += "Second paragraph.\P")
__str__() str

Returns the MTEXT content attribute text.

clear()

Reset the content to an empty string.

font(name: str, bold: bool = False, italic: bool = False) MTextEditor

Set the text font by the font family name. Changing the font height should be done by the height() or the scale_height() method. The font family name is the name shown in font selection widgets in desktop applications: “Arial”, “Times New Roman”, “Comic Sans MS”. Switching the codepage is not supported.

Parameters:
  • name – font family name

  • bold – flag

  • italic – flag

height(height: float) MTextEditor

Set the absolute text height in drawing units.

scale_height(factor: float) MTextEditor

Scale the text height by a factor. This scaling will accumulate, which means starting at height 2.5 and scaling by 2 and again by 3 will set the text height to 2.5 x 2 x 3 = 15. The current text height is not stored in the MTextEditor, you have to track the text height by yourself! The initial text height is stored in the MText entity as DXF attribute char_height.

width_factor(factor: float) MTextEditor

Set the absolute text width factor.

char_tracking_factor(factor: float) MTextEditor

Set the absolute character tracking factor.

oblique(angle: int) MTextEditor

Set the text oblique angle in degrees, vertical is 0, a value of 15 will lean the text 15 degree to the right.

color(name: str) MTextEditor

Set the text color by color name: “red”, “yellow”, “green”, “cyan”, “blue”, “magenta” or “white”.

aci(aci: int) MTextEditor

Set the text color by AutoCAD Color Index (ACI) in range [0, 256].

rgb(rgb: RGB) MTextEditor

Set the text color as RGB value.

underline(text: str) MTextEditor

Append text with a line below the text.

overline(text: str) MTextEditor

Append text with a line above the text.

strike_through(text: str) MTextEditor

Append text with a line through the text.

group(text: str) MTextEditor

Group text, all properties changed inside a group are reverted at the end of the group. AutoCAD supports grouping up to 8 levels.

stack(upr: str, lwr: str, t: str = '^') MTextEditor

Append stacked text upr over lwr, argument t defines the kind of stacking, the space ” ” after the “^” will be added automatically to avoid caret decoding:

"^": vertical stacked without divider line, e.g. \SA^ B:
     A
     B

"/": vertical stacked with divider line,  e.g. \SX/Y:
     X
     -
     Y

"#": diagonal stacked, with slanting divider line, e.g. \S1#4:
     1/4
paragraph(props: ParagraphProperties) MTextEditor

Set paragraph properties by a ParagraphProperties object.

bullet_list(indent: float, bullets: Iterable[str], content: Iterable[str]) MTextEditor

Build bulleted lists by utilizing paragraph indentation and a tabulator stop. Any string can be used as bullet. Indentation is a multiple of the initial MTEXT char height (see also docs about ParagraphProperties), which means indentation in drawing units is MText.dxf.char_height x indent.

Useful UTF bullets:

  • “bull” U+2022 = • (Alt Numpad 7)

  • “circle” U+25CB = ○ (Alt Numpad 9)

For numbered lists just use numbers as bullets:

MTextEditor.bullet_list(
    indent=2,
    bullets=["1.", "2."],
    content=["first", "second"],
)
Parameters:
  • indent – content indentation as multiple of the initial MTEXT char height

  • bullets – iterable of bullet strings, e.g. ["-"] * 3, for 3 dashes as bullet strings

  • content – iterable of list item strings, one string per list item, list items should not contain new line or new paragraph commands.

Constants stored in the MTextEditor class:

NEW_LINE

'\P'

NEW_PARAGRAPH

'\P'

NEW_COLUMN

'\N

UNDERLINE_START

'\L'

UNDERLINE_STOP

'\l'

OVERSTRIKE_START

'\O'

OVERSTRIKE_STOP

'\o'

STRIKE_START

'\K'

STRIKE_STOP

'\k'

ALIGN_BOTTOM

'\A0;'

ALIGN_MIDDLE

'\A1;'

ALIGN_TOP

'\A2;'

NBSP

'\~'

TAB

'^I'

class ezdxf.tools.text.ParagraphProperties(indent=0, left=0, right=0, align=DEFAULT, tab_stops=[])

Stores all known MTEXT paragraph properties in a NamedTuple. Indentations and tab stops are multiples of the default text height MText.dxf.char_height. E.g. char_height is 0.25 and indent is 4, the real indentation is 4 x 0.25 = 1 drawing unit. The default tabulator stops are 4, 8, 12, … if no tabulator stops are explicit defined.

Parameters:
  • indent (float) – left indentation of the first line, relative to left, which means an indent of 0 has always the same indentation as left

  • left (float) – left indentation of the paragraph except for the first line

  • right (float) – left indentation of the paragraph

  • alignMTextParagraphAlignment enum

  • tab_stops – tuple of tabulator stops, as float or as str, float values are left aligned tab stops, strings with prefix "c" are center aligned tab stops and strings with prefix "r" are right aligned tab stops

tostring() str

Returns the MTEXT paragraph properties as MTEXT inline code e.g. "\pxi-2,l2;".

class ezdxf.lldxf.const.MTextParagraphAlignment
DEFAULT
LEFT
RIGHT
CENTER
JUSTIFIED
DISTRIBUTED

Single Line Text

class ezdxf.tools.text.TextLine(text: str, font: fonts.AbstractFont)

Helper class which represents a single line text entity (e.g. Text).

Parameters:
property width: float

Returns the final (stretched) text width.

property height: float

Returns the final (stretched) text height.

stretch(alignment: TextEntityAlignment, p1: Vec3, p2: Vec3) None

Set stretch factors for FIT and ALIGNED alignments to fit the text between p1 and p2, only the distance between these points is important. Other given alignment values are ignore.

font_measurements() fonts.FontMeasurements

Returns the scaled font measurements.

baseline_vertices(insert: UVec, halign: int = 0, valign: int = 0, angle: float = 0, scale: tuple[float, float] = (1, 1)) list[Vec3]

Returns the left and the right baseline vertex of the text line.

Parameters:
  • insert – insertion location

  • halign – horizontal alignment left=0, center=1, right=2

  • valign – vertical alignment baseline=0, bottom=1, middle=2, top=3

  • angle – text rotation in radians

  • scale – scale in x- and y-axis as 2-tuple of float

corner_vertices(insert: UVec, halign: int = 0, valign: int = 0, angle: float = 0, scale: tuple[float, float] = (1, 1), oblique: float = 0) list[Vec3]

Returns the corner vertices of the text line in the order bottom left, bottom right, top right, top left.

Parameters:
  • insert – insertion location

  • halign – horizontal alignment left=0, center=1, right=2

  • valign – vertical alignment baseline=0, bottom=1, middle=2, top=3

  • angle – text rotation in radians

  • scale – scale in x- and y-axis as 2-tuple of float

  • oblique – shear angle (slanting) in x-direction in radians

static transform_2d(vertices: Iterable[UVec], insert: UVec = Vec3(0, 0, 0), shift: tuple[float, float] = (0, 0), rotation: float = 0, scale: tuple[float, float] = (1, 1), oblique: float = 0) list[Vec3]

Transform any vertices from the text line located at the base location at (0, 0) and alignment LEFT.

Parameters:
  • vertices – iterable of vertices

  • insert – insertion location

  • shift – (shift-x, shift-y) as 2-tuple of float

  • rotation – text rotation in radians

  • scale – (scale-x, scale-y) as 2-tuple of float

  • oblique – shear angle (slanting) in x-direction in radians

Functions

ezdxf.tools.text.caret_decode(text: str) str

DXF stores some special characters using caret notation. This function decodes this notation to normalize the representation of special characters in the string.

see: https://en.wikipedia.org/wiki/Caret_notation

ezdxf.tools.text.estimate_mtext_content_extents(content: str, font: fonts.AbstractFont, column_width: float = 0.0, line_spacing_factor: float = 1.0) tuple[float, float]

Estimate the width and height of the MText content string. The result is very inaccurate if inline codes are used or line wrapping at the column border is involved! Column breaks \N will be ignored.

Parameters:
  • content – the MText content string

  • font – font abstraction based on ezdxf.tools.fonts.AbstractFont

  • column_widthMText.dxf.width or 0.0 for an unrestricted column width

  • line_spacing_factorMText.dxf.line_spacing_factor

Returns:

tuple[width, height]

ezdxf.tools.text.estimate_mtext_extents(mtext: MText) tuple[float, float]

Estimate the width and height of a single column MText entity.

This function is faster than the mtext_size() function, but the result is very inaccurate if inline codes are used or line wrapping at the column border is involved!

Returns:

Tuple[width, height]

ezdxf.tools.text.fast_plain_mtext(text: str, split=False) list[str] | str

Returns the plain MTEXT content as a single string or a list of strings if split is True. Replaces \P by \n and removes other controls chars and inline codes.

This function is more than 4x faster than plain_mtext(), but does not remove single letter inline commands with arguments without a terminating semicolon like this "\C1red text".

Note

Well behaved CAD applications and libraries always create inline codes for commands with arguments with a terminating semicolon like this "\C1;red text"!

Parameters:
  • text – MTEXT content string

  • split – split content at line endings \P

ezdxf.tools.text.is_text_vertical_stacked(text: DXFEntity) bool

Returns True if the associated text Textstyle is vertical stacked.

ezdxf.tools.text.is_upside_down_text_angle(angle: float, tol: float = 3.0) bool

Returns True if the given text angle in degrees causes an upside down text in the WCS. The strict flip range is 90° < angle < 270°, the tolerance angle tol extends this range to: 90+tol < angle < 270-tol. The angle is normalized to [0, 360).

Parameters:
  • angle – text angle in degrees

  • tol – tolerance range in which text flipping will be avoided

ezdxf.tools.text.leading(cap_height: float, line_spacing: float = 1.0) float

Returns the distance from baseline to baseline.

Parameters:
  • cap_height – cap height of the line

  • line_spacing – line spacing factor as percentage of 3-on-5 spacing

ezdxf.tools.text.plain_mtext(text: str, split=False, tabsize: int = 4) list[str] | str

Returns the plain MTEXT content as a single string or a list of strings if split is True. Replaces \P by \n and removes other controls chars and inline codes.

This function is much slower than fast_plain_mtext(), but removes all inline codes.

Parameters:
  • text – MTEXT content string

  • split – split content at line endings \P

  • tabsize – count of replacement spaces for tabulators ^I

ezdxf.tools.text.plain_text(text: str) str

Returns the plain text for Text, Attrib and Attdef content.

ezdxf.tools.text.safe_string(s: str | None, max_len: int = MAX_STR_LEN) str

Returns a string with line breaks \n replaced by \P and the length limited to max_len.

ezdxf.tools.text.text_wrap(text: str, box_width: float | None, get_text_width: Callable[[str], float]) list[str]

Wrap text at \n and given box_width. This tool was developed for usage with the MTEXT entity. This isn’t the most straightforward word wrapping algorithm, but it aims to match the behavior of AutoCAD.

Parameters:
  • text – text to wrap, included \n are handled as manual line breaks

  • box_width – wrapping length, None to just wrap at \n

  • get_text_width – callable which returns the width of the given string

ezdxf.tools.text.upright_text_angle(angle: float, tol: float = 3.0) float

Returns a readable (upright) text angle in the range angle <= 90+tol or angle >= 270-tol. The angle is normalized to [0, 360).

Parameters:
  • angle – text angle in degrees

  • tol – tolerance range in which text flipping will be avoided