TextElement

Synthèse

The TextElement object provides access to properties and methods for managing text elements on a layout or in a map graphics layer.

Discussion

The TextElement object represents inserted text on a layout or in a map graphics layer. This includes items such as text, callouts, rectangle text, titles, and so on. It does not include text strings that are part of a legend, table frame, or other map surround elements. The listElements method on the Layout object returns a Python list of page layout element objects. You then must iterate through each item in the list or specify an index number to reference a specific page element object. To return a list of TextElement objects only, use the TEXT_ELEMENT constant for the elementType parameter. A wildcard value can also be used to further refine the search based on the element's name value. Give each text element a unique name so it can be easily referenced.

There are two methods to create text elements. The first is the createTextElement method on the ArcGISProject object, which allows you to create a text element in a layout or graphics layer using Point, Polygon, or Polyline geometry. The second method is to clone existing text elements using the clone method on the TextElement object. This is useful because, in some cases, it is easier to start with an existing element. When cloning an element, provide a suffix value so that cloned elements can be identified later using the listElements method using a wildcard and the same suffix value. The returned list of elements can be further modified or deleted using the delete method.

The elementPositionX and elementPositionY values are based on the element's anchor position, which is set on the Format tab in ArcGIS Pro. Anchor positions can be modified using the setAnchor method. It is important to understand the difference between the elementRotation and textAngle properties. The best example is with inserted rectangle text. The elementRotation property controls the rotation of the rectangle, and the textAngle property controls the angle of the text in the rectangle. For point text, both values are synchronized regardless of which property is set.

Text elements have getDefinition and setDefinition methods that allow you to modify additional properties that are not exposed to the TextElement class. See the Python CIM access help topic for more information.

Propriétés

PropriétéExplicationType de données
anchor
(Lecture seule)

Returns one of the following string values that represent the current anchor position. To change the value, use the setAnchor method.

  • BOTTOM_LEFT_CORNERThe current anchor position is the bottom left corner position.
  • BOTTOM_MID_POINTThe current anchor position is the bottom center position.
  • BOTTOM_RIGHT_CORNERThe current anchor position is the bottom right corner position.
  • CENTER_POINTThe current anchor position is the center position.
  • LEFT_MID_POINTThe current anchor position is the left center position.
  • RIGHT_MID_POINTThe current anchor position is the right center position.
  • TOP_LEFT_CORNERThe current anchor position is the top left corner position.
  • TOP_MID_POINTThe current anchor position is the top center position.
  • TOP_RIGHT_CORNERThe current anchor position is the top right corner position.
String
elementHeight
(Lecture et écriture)

The height of the element in page units.

Double
elementPositionX
(Lecture et écriture)

The x-location of the element's anchor position. The units assigned or reported are in page units.

Double
elementPositionY
(Lecture et écriture)

The y-location of the element's anchor position. The units assigned or reported are in page units.

Double
elementRotation
(Lecture et écriture)

The element's rotation angle in degrees. Positive values rotate clockwise and negative values rotate counterclockwise.

Double
elementWidth
(Lecture et écriture)

The width of the element in page units.

Double
fontFamilyName
(Lecture et écriture)

The text symbol font associated with the element.

Remarque :

The value that appears in the Font name drop-down list on the ribbon does not always match the font_style_name property. Variable fonts contain named instances of font styles and also allow customization. Before setting a value, you can set it on the ribbon and verify the property value returned.

String
fontStyleName
(Lecture et écriture)

Depending on the font, the styles may include regular, bold, italic, any combination of these, or an extended list.

Remarque :

The value that appears in the Font style drop-down list on the ribbon does not always match the font_style_name property. Variable fonts contain named instances of font styles and also allow customization. Before setting a value, you can set it on the ribbon and verify the property value returned.

String
isOverflowing
(Lecture seule)

Returns True if the text does not fit within the boundaries of the geometry provided. This is typically displayed with red ellipsis on a layout. This allows you to change the font size or increase the geometry the text is being fit to.

Boolean
locked
(Lecture et écriture)

When set to True, the element cannot be graphically selected in the layout view.

Boolean
name
(Lecture et écriture)

The name of the element. It is important that all elements have a unique name so they can be easily referenced.

String
text
(Lecture et écriture)

The text string associated with the element.

String
textAngle
(Lecture et écriture)

The angle in degrees the text string is rotated. Positive values rotate clockwise and negative values rotate counterclockwise.

Double
textSize
(Lecture et écriture)

The element text size in points.

Double
type
(Lecture seule)

Returns a value of TEXT_ELEMENT.

String
visible
(Lecture et écriture)

Specifies whether the element is visible in the layout or graphics layer.

Boolean

Vue d’ensemble des méthodes

MéthodeExplication
clone ({suffix})

Provides a mechanism to clone an existing text element on a page layout.

delete ()

Provides a mechanism to delete an existing text element on a page layout.

getDefinition (cim_version)

Returns a text element's CIM definition.

setAnchor (anchor)

The setAnchor method controls the anchor position.

setDefinition (definition_object)

Sets a text element's CIM definition.

Méthodes

clone ({suffix})
ParamètreExplicationType de données
suffix

An optional string that is used to tag each newly created text element. The new element gets the same element name as the parent text element, plus the suffix value, plus a numeric sequencer. For example, if the parent element name is FieldLabel and the suffix value is _copy, the newly cloned elements are named FieldLabel_copy, FieldLabel_copy_1, FieldLabel_copy_2, and so on. If a suffix is not provided, the results resemble FieldLabel_1, FieldLabel_2, FieldLabel_3, and so on.

String

Grouped text elements can't be cloned. All grouped elements are graphic element types. Verify if a graphic element is grouped by using the isGroup property on the GraphicElement object.

delete ()

It may be necessary to delete existing or cloned text elements. Cloned elements, when created, can be given a custom suffix so they can be easy to find when using the wildcard parameter for the listElements method on the Layout object.

getDefinition (cim_version)
ParamètreExplicationType de données
cim_version

A string that represents the major version of the CIM that will be used.

  • V2The 2.x version of the CIM will be used.
  • V3The 3.x version of the CIM will be used.
String
Valeur renvoyée
Type de donnéesExplication
Object

Returns the CIM definition for a TextElement.

For more information about working with the CIM and samples, see Python CIM access.

setAnchor (anchor)
ParamètreExplicationType de données
anchor

A string that specifies an anchor position.

  • BOTTOM_LEFT_CORNERThe anchor will be set at the bottom left corner position.
  • BOTTOM_MID_POINTThe anchor will be set at the bottom center position.
  • BOTTOM_RIGHT_CORNERThe anchor will be set at the bottom right corner position.
  • CENTER_POINTThe anchor will be set at the center position.
  • LEFT_MID_POINTThe anchor will be set at the left center position.
  • RIGHT_MID_POINTThe anchor will be set at the right center position.
  • TOP_LEFT_CORNERThe anchor will be set at the top left corner position.
  • TOP_MID_POINTThe anchor will be set at the top center position.
  • TOP_RIGHT_CORNERThe anchor will be set at the top right corner position.
String

Setting the anchor position allows you to control how the element might expand with additional text. For example, setting the anchor position to CENTER_POINT with point text is useful for dynamic strings you want to keep centered such as a title at the top of a layout.

setDefinition (definition_object)
ParamètreExplicationType de données
definition_object

A modified CIM definition object originally retrieved using getDefinition.

Object

For more information about working with the CIM and samples, see Python CIM access.

Exemple de code

TextElement example 1

The following script replaces 2022 with 2023 in all layout text element strings that contain the year in all layouts in a project.

import arcpy

search_text = '2022'
replace_text = '2023'

p = arcpy.mp.ArcGISProject(r'C:\Projects\YosemiteNP\Yosemite.aprx')
for lyt in p.listLayouts():
  for txt in lyt.listElements('TEXT_ELEMENT'):
    if search_text in txt.text:
      print(f'For element: "{txt.name}" in layout: "{lyt.name}"')
      print(f'  Replacing: "{txt.text}"')
      txt.text = txt.text.replace(search_text, replace_text)
      print(f'  With: "{txt.text}"')
  print('')
  
p.save()
TextElement example 2

The following script creates a layout and creates a text element using a system style item. Next, it changes the anchor position so when text is resized, it will stay centered on the layout. Finally, it resizes the text to fit the width of the layout, with a 10% buffer from the edges.

p = arcpy.mp.ArcGISProject('current')

#Create a layout
lyt = p.createLayout(8.5, 11, 'INCH', 'New Layout with Point Text')
lyt.openView()

#Create point text element using a system style item
txtStyleItem = p.listStyleItems('ArcGIS 2D', 'TEXT', 'Title (Serif)')[0]
ptTxt = p.createTextElement(lyt, arcpy.Point(4.25, 10), 'POINT',
                            'Fit My Title To Layout Width, Less 10%',
                            10, style_item=txtStyleItem)

#Change the anchor position and reposition the text to center
ptTxt.setAnchor('Center_Point')
ptTxt.elementPositionX = 4.25
ptTxt.elementPositionY = 10

#Adjust text size to fit the width of the layout
while ptTxt.elementWidth < (lyt.pageWidth - (lyt.pageWidth * 0.1)):
  ptTxt.textSize = ptTxt.textSize + 0.1
TextElement example 3

The following script creates a map, adds a layer file, and creates a graphics layer. It then iterates through each feature in the layer and generates a map graphic text element based on the feature's name value.

p = arcpy.mp.ArcGISProject('current')

#Create a map, add a layer file and create a graphics layer
m = p.createMap('New Map with Text Graphics', 'Map')
lyrFile = arcpy.mp.LayerFile(r'C:\Projects\GreatLakes\GreatLakes_CenterPts.lyrx')
m.addLayer(lyrFile)
lyr = m.listLayers('GreatLakes_CenterPoint')[0]
gl = m.createGraphicsLayer('New Graphics Layer')

#Create a map graphic at each point location using each feature's name value
txtStyleItem = p.listStyleItems('ArcGIS 2D', 'TEXT', 'Water (Large)')[0]
for row in arcpy.da.SearchCursor(lyr, ['SHAPE@XY', 'NAME']):
  x, y = row[0]
  txt = p.createTextElement(gl, arcpy.Point(x,y), 'POINT', row[1])

m.openView()
TextElement example 4

The following script uses a JSON template to create a curve (arc) and a Bézier geometry. The geometries are used to create two graphic elements and two text elements in a new layout. Optionally, Python CIM access is used to modify the Bézier curve properties. For more information about creating geometry objects using JSON, see the Geometry objects developer help topic.

p = arcpy.mp.ArcGISProject('current')
lyt = p.createLayout(6, 3, 'INCH', 'New Layout with 2 curves')

#Construct a curve/arc graphic element using a default symbol
arcPath = {"curvePaths" : [[[3.5,1.25],{"c" : [[5,1.25],[4.25, 1.75]]}]]}
arc = arcpy.AsShape(arcPath, esri_json=True)
arcGra = p.createGraphicElement(lyt, arc, name='ArcPy_Arc')
arcTxt = p.createTextElement(lyt, arc, 'LINE', 'Arc-e-Text', 24, 'Comic Sans MS', name='ArcPy_ArcText')

#Construct a bezier curve graphic element using a system style item
curveStyle = p.listStyleItems('ArcGIS 2D', 'Line', 'Dashed 1 Long 1 Short')[0]
curvePath = {"curvePaths" : [[[1.25,1.25],
                              {"b" : [[3,1.5],[1.6875,2.75],[2.125,0]]}]]}
curve = arcpy.AsShape(curvePath, esri_json=True)
curveGra = p.createGraphicElement(lyt, curve, curveStyle, 'ArcPy_Curve')
curveTxt = p.createTextElement(lyt, curve, 'LINE', 'Curved text', 24, 'Comic Sans MS', name='ArcPy_CurveText')

#Optional CIM modification
curveTxt_cim = curveTxt.getDefinition('V3')
curveTxt_cim.symbol.symbol.verticalAlignment = 'Center'
curveTxt.setDefinition(curveTxt_cim)

lyt.openView()
TextElement example 5

The following script creates a rectangle graphic and text element in a new layout. The text string is intentionally long so it can demonstrate how to resize the text to fit the rectangle. A function is used to create the rectangle, and the isOverflowing property is used to determine whether the text fits in the geometry.

def MakeRec_UL(ulx, uly, w, h):
    xyRecList = [[ulx, uly], [ulx+w, uly], [ulx+w,uly-h], [ulx,uly-h], [ulx,uly]]
    array = arcpy.Array([arcpy.Point(*coords) for coords in xyRecList])
    rect = arcpy.Polygon(array)
    return rect

p = arcpy.mp.ArcGISProject('current')

#Create a layout
lyt = p.createLayout(8.5, 11, 'INCH', 'New Layout with Rectangle Text')
lyt.openView()

#Rectangle Text
text = '''THIS TEXT WILL BE REDUCED UNTIL ALL THE TEXT FITS IN THE RECTANGLE AREA.
  AGAIN - THIS  TEXT WILL BE REDUCED UNTIL ALL THE TEXT FITS IN THE RECTANGLE AREA.
  AND AGAIN - THIS TEXT WILL BE REDUCED UNTIL ALL THE TEXT FITS IN THE RECTANGLE AREA.'''
recTxt = p.createTextElement(lyt, MakeRec_UL(0.5, 10.5, 7.5, 1), 'POLYGON',
                             text, 25, 'Arial', 'Regular', name='ArcPy_RecText') 

#Reduce text to fix rectangle
while recTxt.isOverflowing:
    recTxt.textSize = recTxt.textSize - 1
TextElement example 6

The following script creates a custom polygon graphic and text element in a new layout. The text string is intentionally long so it can demonstrate how it wraps to the geometry as well as how it resizes so the text fits the shape using the isOverflowing property. The script also demonstrates how to use Python CIM access to set the text element's background and border symbology.

p = arcpy.mp.ArcGISProject('current')

#Create a layout
lyt = p.createLayout(8.5, 11, 'INCH', 'New Layout with Polygon Text')
lyt.openView()

#Polygon Text
polyCoords = [[0.5, 10], [4.25, 10], [4.25, 9.5], [8, 9.5], [8, 8.5], [0.5, 8.5], [0.5, 10]]
polyShp = arcpy.Polygon(arcpy.Array([arcpy.Point(*coords) for coords in polyCoords]))
text = 'Some Text String that is really long and is <BOL>forced to wrap to other \
lines</BOL> so that we can see how it fits the polygon shape provided to the function.'
polyTxt = p.createTextElement(lyt, polyShp, 'POLYGON', text, 25,
                              'Arial', 'Regular', name='ArcPy_PolygonText')

#Reduce text to fit shape
while polyTxt.isOverflowing:
  polyTxt.textSize = polyTxt.textSize - 1

#OPTIONAL CIM modifications
polyTxt_cim = polyTxt.getDefinition('V3')

#CIM Change text color
polyTxt_cim.symbol.symbol.symbol.symbolLayers[0].color.values = [0,0,255,100]
        
#CIM Create a graphic frame background symbol
bgRGBColor = arcpy.cim.CreateCIMObjectFromClassName('CIMRGBColor', 'V3')
bgRGBColor.values = [225, 225, 225, 100]
bgSolidFillLyr = arcpy.cim.CreateCIMObjectFromClassName('CIMSolidFill', 'V3')
bgSolidFillLyr.color = bgRGBColor
bgPolySym = arcpy.cim.CreateCIMObjectFromClassName('CIMPolygonSymbol', 'V3')
bgPolySym.symbolLayers = [bgSolidFillLyr]
bgSymRef = arcpy.cim.CreateCIMObjectFromClassName('CIMSymbolReference', 'V3')
bgSymRef.symbol = bgPolySym
GraphicFrame = arcpy.cim.CreateCIMObjectFromClassName('CIMGraphicFrame', 'V3')
GraphicFrame.backgroundSymbol = bgSymRef
        
#CIM Create a graphic frame border symbol
brdRGBColor = arcpy.cim.CreateCIMObjectFromClassName('CIMRGBColor', 'V3')
brdRGBColor.values = [255, 0, 0, 100]
brdSolidStrokeLyr = arcpy.cim.CreateCIMObjectFromClassName('CIMSolidStroke', 'V3')
brdSolidStrokeLyr.color = brdRGBColor
brdSolidStrokeLyr.miterLimit = 10
brdSolidStrokeLyr.width = 5
brdLineSym = arcpy.cim.CreateCIMObjectFromClassName('CIMLineSymbol', 'V3')
brdLineSym.symbolLayers = [brdSolidStrokeLyr]
brdSymRef = arcpy.cim.CreateCIMObjectFromClassName('CIMSymbolReference', 'V3')
brdSymRef.symbol = brdLineSym
GraphicFrame.borderSymbol = brdSymRef

polyTxt_cim.frame = GraphicFrame
polyTxt.setDefinition(polyTxt_cim)
TextElement example 7

The following script constructs a graphic table based on data values from a table in a map. The layout was authored with a vertical line named vertLine, a horizontal line named horzLine, and a text element named cellText. Each element was authored with the appropriate symbology and text properties. The element's anchors were set to the upper left position, and the text element's vertical and horizontal justification were set to upper left.

def MakeRec_LL(llx, lly, w, h):
    xyRecList = [[llx, lly], [llx, lly+h], [llx+w,lly+h], [llx+w,lly], [llx,lly]]
    xyRecList = [[1,1],[1, 2], [2.75, 2], [2.75, 1], [1, 1]]
    array = arcpy.Array([arcpy.Point(*coords) for coords in xyRecList])
    rec = arcpy.Polygon(array)
    return rec

p = arcpy.mp.ArcGISProject('CURRENT')

#Create a layout
lyt = p.createLayout(6, 3, 'INCH', 'New Layout with Rectangles')

#Construct a pre-defined rectangle graphic element using a system style item
# and a rectangle function that takes x/y min/max and a width/height
# using the lower left corner as a start location

polyStyle = p.listStyleItems('ArcGIS 2D', 'Polygon', 'Orchard')[0]

p.createPredefinedGraphicElement(lyt, MakeRec_LL(1, 1, 1.75, 1), 'RECTANGLE',
                                 polyStyle, 'ArcPy_Rectangle_Env',
                                 lock_aspect_ratio=False)

#Construct the same element above using a point location
rec = p.createPredefinedGraphicElement(lyt, arcpy.Point(3, 1), 'RECTANGLE',
                                       polyStyle, 'ArcPy_Rectangle_Pt',
                                       lock_aspect_ratio=False)
rec.elementWidth = 1.75
rec.elementHeight = 1

lyt.openView()