I'm having a strange problem with a script. I have a template MXD set up with a bunch of text elements set up that I will be updating by adding values from a search cursor. The script is to generate a soils by parcel report for non-tillable vs tillable Ag Land with adjusted CSR (Corn Suitability Rate) values. Everything in my script works correctly except that all the labels (except roads) disappear when the map is exported to a PDF.I cannot find anything in my script that would be causing the labels to disappear. My first guess was that it had something to do with updating a bunch of text elements, but I ruled this out when I exported 2 PDF's (a test map BEFORE updating text elements and then the final version). Labels were not present in both PDF's. To update the text elements, I just created a dictionary where the text elements are the keys, and I add values from a search cursor on the selected parcel by concatenating the value to the original text element for the report. All my text elements come out correctly but no labels on the map. I am thoroughly confused. Here is my script:
'''
Generates Soil by parcel report for the new Ag Land Adjustment
Written by: Caleb Mackey
Date: 5/3/2013
Cedar County
'''
import arcpy, os
from os import path as p
from arcpy import mapping as m
from MemoryTableToolsDA import * # Custom module
from Gmail_tools import SendGmailMessage # Custom module
import subprocess
arcpy.env.overwriteOutput = True
print 'One moment please...'
def Menu():
pid = raw_input('Type Parcel ID and hit Enter\n')
GenerateSoilReport(pid)
choice = raw_input('\nSearch another parcel? (y,n)\n').lower()
if choice == 'y':
Menu()
else:
return 0
def GenerateSoilReport(parcel_id):
# Locals
mapDoc = r'G:\PROJECTS\Cedar\Soils\AgLand_Report.mxd'
mailing = r'G:\Data\Geodatabase\Cedar_County.gdb\Mailing_List'
pars = r'G:\PROJECTS\Cedar\Soils\testing\CSR_AgLand_test.gdb\dissolve'
address = r'G:\Data\Geodatabase\Cedar_County.gdb\ADDRESS\Addresses'
realdata = r'G:\Data\Database\Cedar.gdb\REALDATA'
fold = r'G:\PROJECTS\Cedar\Soils\Layers'
symblyr = p.join(fold,'Selected_Parcel.lyr')
# Copy soil summary parcels and add mailing info
## tmp = r'in_memory\Selected_Parcel' # having problems with this
tmp = r'G:\PROJECTS\Cedar\Soils\testing\Intersect_files.gdb\Selected_Parcel'
query = '"PID" = \'%s\'' %parcel_id
arcpy.Select_analysis(pars, tmp, query)
if int(arcpy.GetCount_management(tmp).getOutput(0)) != 1:
print 'Invalid PID, seleced %s parcels...please try again' %result
Menu() # call Menu
# Copy fields (Custom tool)
CopyFields(tmp, 'PID', mailing, 'PID', ['NAME','MAILING_ADDRESS','CITY_ST_ZIP'])
CopyFields(tmp, 'PID', address, 'PID', ['FULL_ADD', 'CITY', 'ZIP'])
CopyFields(tmp, 'PID', realdata, 'PARCELPIN', ['DEEDHOLDER','LEGAL'])
# Create MXD object
mxd = m.MapDocument(mapDoc)
df = m.ListDataFrames(mxd, 'Layers')[0]
# Create new layer file and add to MXD
lyr = m.Layer(tmp)
arcpy.ApplySymbologyFromLayer_management(lyr,symblyr)
m.AddLayer(df, lyr, 'TOP')
try:
lyr = m.ListLayers(mxd, 'Selected_Parcel', df)[0]
except:
print 'Layer not found!\n\n' # does not find layer if created from in_memory source
for layer in m.ListLayers(mxd, '*', df):
print layer.name
# Select for zoom
arcpy.SelectLayerByAttribute_management(lyr, 'NEW_SELECTION', query)
df.zoomToSelectedFeatures()
print 'Selected %s parcel.' %int(arcpy.GetCount_management(lyr).getOutput(0))
df.scale *= 1.3
arcpy.SelectLayerByAttribute_management(lyr, 'CLEAR_SELECTION')
arcpy.RefreshActiveView()
arcpy.RefreshTOC()
# CLASSCODE dictionary
class_dict = {0 : 'Ag Land', 1 : 'Ag Dwelling', 2 : 'Residential',
3 : 'Commercial', 4 : 'Industrial', 5 : 'Exempt',
6 : 'Other'}
# Generate text element dictionary
fields = ['SUM_CSR_Points','SUM_Unadjusted_CSR_Points','AVE_CSR','ACRES',
'DEEDHOLDER','Point_Deduction','Percent_Change','CLASSCODE',
'NAME','MAILING_ADDRESS','CITY_ST_ZIP','FULL_ADD','CITY','ZIP',
'LEGAL', 'PID']
# Get rid of NULLs
with arcpy.da.UpdateCursor(lyr,['NAME','MAILING_ADDRESS','CITY_ST_ZIP']) as rows:
for r in rows:
if r[0] == None:
r[0] = ''
if r[1] == None:
r[1] = ''
if r[2] == None:
r[2] = ''
rows.updateRow(r)
# Generate elm_dict
elm_dict = {}
with arcpy.da.SearchCursor(lyr, fields) as rows:
for r in rows:
elm_dict['Adjusted CSR Points: '] = round(r[0],2)
elm_dict['Unadjusted CSR Points: '] = round(r[1],2)
elm_dict['Weighted Average CSR: '] = round(r[2],2)
elm_dict['Acres: '] = r[3]
elm_dict['Deedholder: '] = r[4][:30]
elm_dict['Point Deduction: '] = round(r[5],2)
elm_dict['Percent Change: '] = round(r[6],2)
elm_dict['Parcel Class: '] = class_dict[r[7]]
elm_dict['ML'] = '\n'.join([r[8][:30],r[9],r[10].split('-')[0]])
try:
elm_dict['PA'] = '\n'.join([r[8][:30],r[11]]) +'\n%s, IA %s'.title() %(r[12],r[13].split('-')[0])
except:
elm_dict['PA'] = 'No Situs Address'
elm_dict['Legal Description: '] = r[14][:30]
elm_dict['PID: '] = r[15]
# Loop thru Text elms and add values
for elm in m.ListLayoutElements(mxd, 'TEXT_ELEMENT'):
if elm.text not in ['Mailing Address','Property Address']:
if elm.text in ['PA','ML']:
elm.text = str(elm_dict[elm.text.encode('utf-8')])
else:
elm.text += str(elm_dict[elm.text.encode('utf-8')])
print 'Updated all text elements'
arcpy.RefreshActiveView() # tried to refresh here again hoping that would fix the problem...did not work
# -----------------------------------------------------------------------------------------------
# Export map to PDF and print (option to email)
# PDF name
pdf_path = r'G:\PROJECTS\Cedar\Soils\Customer_Maps'
PDF = p.join(pdf_path, 'Parcel_%s.pdf' %parcel_id)
print 'Exporting to pdf...'
if arcpy.Exists(PDF):
arcpy.Delete_management(PDF)
# Export map document object to pdf
m.ExportToPDF(mxd, PDF)
del mxd
# Return message to user
print 'PDF Exported, to view open %s in the "Customer_Maps" folder.' % p.basename(PDF)
print 'Sending document to default printer'
# Locate AcroRd32.exe
if p.exists(r"C:\Program Files (x86)\Adobe"):
acroread = r"C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe"
else:
acroread = r"C:\Program Files\Adobe\Reader 11.0\Reader\AcroRd32.exe"
## # # # Print PDF # # #
## cmd = '"%s" /N /T "%s"' %(acroread,PDF)
## proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
# Leave these out for now
#stdout,stderr=proc.communicate()
#exit_code=proc.wait()
print 'Successful'
# E-Mail PDF to customer option (Custom tool)
email = raw_input('\nWould you like to email this document? (y,n)\n')
if email.lower() == 'y':
em_add = raw_input('\nPlease type email address to send document\n')
outname = 'CSR Report for Property Deeded to: '+ elm_dict['Deedholder: '].split(' ')[0]
message = 'Hello,\n\nPlease see enclosed PDF document for the following {0}.\n' \
.format(outname)
subject = '%s' %outname
attach = [] # attachments must be in list
attach.append(PDF)
SendGmailMessage(message, subject, em_add, attach)
if __name__ == '__main__':
# Start Program
Menu()
I am attaching a before png of what the template mxd looks like (with all the labels) then the final product after I run the script and all the labels disappear. I have tried everything I can think of and no matter what I do the labels are disappearing. I have brought this to the attention of an Esri Analyst, but I do not think they have found a solution yet either... Has anyone else had this problem?[ATTACH=CONFIG]24069[/ATTACH][ATTACH=CONFIG]24070[/ATTACH][ATTACH=CONFIG]24071[/ATTACH]ArcGIS Standard 10.1 SP 1, Windows 7 64 bit SP 1EDIT: In case anyone is wondering why the placement of text elements/data frames is slightly different between the two maps it is because I tested this with several different versions of the mxd in case the original was somehow corrupted, but I got the same results on the test mxd as well.