Friday 14 February 2020

arcmap - Inserting newlines in Rectangle Text elements via ArcPy causes overlap?


I ran across an issue the other day when I tried to use ArcPy's mapping module to edit rectangle text elements with newlines (\n) in an ArcMap document. Here's what the output looked like:


enter image description here


Here's the code I used to generate that output. The first column are rectangle text elements Text1, Text2, Text3 going down; the second column are "plain" text elements Text4, Text5, and Text6 going down.


import os
import arcpy

HomeDir = r"C:\Desktop"
arcpy.env.workspace = HomeDir


CurrentMXD = arcpy.mapping.MapDocument(r"C:\Desktop\TextTest.mxd")
OutputFilename = r"C:\Desktop\TextTest.pdf"
if os.path.exists(OutputFilename):
os.remove(OutputFilename)

for TextElement in arcpy.mapping.ListLayoutElements(CurrentMXD, "TEXT_ELEMENT"):
TextElementName = TextElement.name

String1 = "The quick brown fox jumped over the lazy dog.\nShe sells sea shells by the sea shore."
String2 = "The quick brown fox \njumped over the lazy dog.\nShe sells sea shells by the sea shore."

String3 = "The quick brown fox jumped \nover the lazy dog.\nShe sells sea shells by the sea shore."

if TextElementName == "Text1":
TextElement.text = String1
if TextElementName == "Text2":
TextElement.text = String2
if TextElementName == "Text3":
TextElement.text = String3
if TextElementName == "Text4":
TextElement.text = String1

if TextElementName == "Text5":
TextElement.text = String2
if TextElementName == "Text6":
TextElement.text = String3

arcpy.mapping.ExportToPDF(CurrentMXD, OutputFilename)

So far, it looks like the presence of the messed up text depends on whether the line is longer enough to wrap, and whether the line before the newline is longer than the line after the newline.


Any ideas about what could be going wrong? Is there a workaround? I could use plain text elements and worry about wrapping lines using Python, but I'm hoping I can figure something out.



Answer




I ran into this as well. It's because ArcGIS requires Windows line endings which are both a carriage return and a line feed. Bit of a pain. Fortunately it's easy to get around. In Python by instead of just \n (which is linefeed - see the Python docs for more if you're keen), use \r\n.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...