Monday, December 5, 2011

Fitting Text in Page Elements Based on Sentence Length

When working with Page Layout and Map Automation, sometimes you want to let the user pass some random text into a text element, but you need to format the text so it doesn't look like one big line of mush.

For this example assume you have a page layout and the maximum length a text item can be is 90 characters.  To format this correctly, you need to check if the values provided are less than 90 characters, if it is, write it, if not, start a new line.

sentence = "No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise please start a new thread in this forum instead."
lineLength = 90
count = 0
currentLine =""
lines = []
for word in str(sentence).split(" "):
    wordLength = len(word + " ")
    if (count + 1) < lineLength:
        currentLine = currentLine + word + " "
        lines.append(currentLine.strip() + "\n")
        currentLine = word + " "
        count = 0
    count += wordLength
lines.append(currentLine.strip() + "\n") 

So I took some test from a random forums I was reading and used that as my dummy text.  At the end of each sentence when I reach the 90 character limit or when the next word will push the line over the 90 character limit, I add a '\n' which will signal for a newline.
Now, put the text in a text element:

mxd = arcpy.mapping.MapDocument("CURRENT")
elem = arcpy.mapping.ListLayoutElements(mxd,"TEXT_ELEMENT","txtTestLength")[0]
elem.text = ""
for line in lines:
    elem.text += line

The arcpy.RefreshActiveView() is essential to use in order to see the new text.  If there is a better way, post it in the comments.

Enjoy and Happy Mapping!