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) ezdxf.tools.text.MTextEditor

Append text.

__iadd__(text: str) ezdxf.tools.text.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) ezdxf.tools.text.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) ezdxf.tools.text.MTextEditor

Set the absolute text height in drawing units.

scale_height(factor: float) ezdxf.tools.text.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) ezdxf.tools.text.MTextEditor

Set the absolute text width factor.

char_tracking_factor(factor: float) ezdxf.tools.text.MTextEditor

Set the absolute character tracking factor.

oblique(angle: int) ezdxf.tools.text.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) ezdxf.tools.text.MTextEditor

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

aci(aci: int) ezdxf.tools.text.MTextEditor

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

rgb(rgb: Tuple[int, int, int]) ezdxf.tools.text.MTextEditor

Set the text color as RGB value.

underline(text: str) ezdxf.tools.text.MTextEditor

Append text with a line below the text.

overline(text: str) ezdxf.tools.text.MTextEditor

Append text with a line above the text.

strike_through(text: str) ezdxf.tools.text.MTextEditor

Append text with a line through the text.

group(text: str) ezdxf.tools.text.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 = '^') ezdxf.tools.text.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: ezdxf.tools.text.ParagraphProperties) ezdxf.tools.text.MTextEditor

Set paragraph properties by a ParagraphProperties object.

bullet_list(indent: float, bullets: Iterable[str], content: Iterable[str]) ezdxf.tools.text.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: ezdxf.tools.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: str, 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() ezdxf.tools.fonts.FontMeasurements

Returns the scaled font measurements.

baseline_vertices(insert, halign, valign, angle, scale) 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, halign, valign, angle, scale, oblique) 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, insert, shift, rotation, scale, oblique) 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.plain_text(text: str) str

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

ezdxf.tools.text.fast_plain_mtext(text: str, split=False) Union[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.plain_mtext(text: str, split=False, tabsize: int = 4) Union[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.text_wrap(text: str, box_width: Optional[float], 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.caret_decode(text: str) str

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

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

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

Returns True if the associated text Textstyle is vertical stacked.