def plot_with_arcpy(init_time, replace_workspace_dir,origin_workspace_dir, images_dir, mxd_path, resolution=100): mxd = mp.MapDocument(mxd_path) # 修改预报时效 txts = mp.ListLayoutElements(mxd, "TEXT_ELEMENT") init_time_datetime = datetime.datetime.strptime(init_time, '%y%m%d%H') for valid_h, i in zip(range(0, 132, 12), range(23, 12, -1)): beg = (init_time_datetime + datetime.timedelta(hours=valid_h)).strftime('%d%H') end = (init_time_datetime + datetime.timedelta(hours=valid_h + 12)).strftime('%d%H') txts[i].text = beg + '-' + end # 替换数据源 mxd.replaceWorkspaces(origin_workspace_dir, "RASTER_WORKSPACE", replace_workspace_dir, "RASTER_WORKSPACE", False) # 处理缺失数据 broken_lyrs = mp.ListBrokenDataSources(mxd) for broken_lyr in broken_lyrs: # 让缺失数据图层及与其同在一个dataframe里其他的图层不显示 broken_df = mp.ListDataFrames(mxd, broken_lyr.name) if len(broken_dfs) > 0: lyrs_in_broken_df = mp.ListLayers(mxd, "", broken_df[0]) for lyr in lyrs_in_broken_df: lyr.visible = False #mxd.save() 不要保存 mp.ExportToJPEG(mxd, os.path.join(images_dir, init_time), resolution=resolution)
def print_map(mxd, pagename, output_type, output_file): """Set up a page and print it. """ arcpy.SetProgressorLabel("Exporting to %s" % output_file) update_page_layout(mxd, pagename) if os.path.exists(output_file): os.unlink(output_file) msg = "" if output_type == 'PDF': try: MAP.ExportToPDF(mxd, output_file) msg = "Completed %s" % output_file except Exception as e: msg = "Export to PDF failed with '%s'." % e pass else: try: MAP.ExportToJPEG(mxd, output_file) msg = "Completed %s" % output_file except Exception as e: msg = "Export to JPEG failed with '%s'." % e pass aprint(msg) return
def exportMap(parameter): inMap = parameter[0] outMap = parameter[1] formatMap = parameter[2] arcpy.env.overwriteOutput = True mxd = mapping.MapDocument(inMap) mxd.activeView = 'PAGE_LAYOUT' if formatMap == 'JPEG': mapping.ExportToJPEG(mxd, outMap) if formatMap == 'PDF': mapping.ExportToPDF(mxd, outMap) if formatMap == 'BMP': mapping.ExportToBMP(mxd, outMap) if formatMap == 'PNG': mapping.ExportToPNG(mxd, outMap) if formatMap == 'TIFF': mapping.ExportToTIFF(mxd, outMap) if formatMap == 'GIF': mapping.ExportToGIF(mxd, outMap) else: mapping.ExportToJPEG(mxd, outMap)
def output_image(self, image_name): """ Factory method for exporting different image types in ArcMap :param str image_name: Name of output image with file extension :return: """ if image_name.endswith("jpg"): mapping.ExportToJPEG( self.mxd, os.path.join(self.output_location, image_name)) # Add other image outputs if needed self.update_status_message() self.output_message("Process Completed")
def zoomExtractMXD(parcel): #Variables mxd = MAP.MapDocument(mxdC) df = MAP.ListDataFrames(mxd)[0] parcelLyr = MAP.ListLayers(mxd, "Parcels", df)[0] jpg = os.path.join(outJPG, "%s") % (parcel) #Update Layers whereClause = "ACCOUNT ='%s'" % parcel arcpy.SelectLayerByAttribute_management(parcelLyr, "NEW_SELECTION", whereClause) #Make sure Account Exists getCount = arcpy.GetCount_management(parcelLyr) theCount = int(getCount.getOutput(0)) if theCount >= 1: df.extent = parcelLyr.getSelectedExtent(True) df.scale *= 1.1 #Update Text updatetext1 = MAP.ListLayoutElements(mxd, "TEXT_ELEMENT", "ACCOUNT")[0] updatetext1.text = parcel #Export to JPG MAP.ExportToJPEG(mxd, jpg) #Release MXD del mxd else: noAcctLog()
print(item.name) # 5 导出地图为PDF文件 import arcpy.mapping as mapping mxd = mapping.MapDocument( r"E:\ArcPyStudy\Data\ArcpyBook\Ch2\Crime_Ch2_new.mxd") mapping.ExportToPDF(mxd, r"E:\ArcPyStudy\Data\ArcpyBook\Ch2\Crime_Ch2_new.pdf") print("Export Done") # 6 导出地图为图像文件 import arcpy.mapping as mapping mxd = mapping.MapDocument( r"E:\ArcPyStudy\Data\ArcpyBook\Ch2\Crime_Ch2_new.mxd") for df in mapping.ListDataFrames(mxd): if df.name == "Crime": mapping.ExportToJPEG( mxd, r"E:\ArcPyStudy\Data\ArcpyBook\Ch2\Crime_Ch2_new.jpg", df) print("Export Done") # 7 导出报表 # 报错 # import arcpy.mapping as mapping # mxd = mapping.MapDocument(r"E:\ArcPyStudy\Data\ArcpyBook\Ch2\Crime_Ch2_new.mxd") # # df = mapping.ListDataFrames(mxd)[0] # # lyr = mapping.ListLayers(mxd,"Crime*",df)[0] # layer = mapping.Layer(r"E:\ArcPyStudy\Data\ArcpyBook\data\School_Districts.lyr") # mapping.ExportReport(layer, # r"E:\ArcPyStudy\Data\ArcpyBook\Ch4\CrimeReport.rlf", # r"E:\ArcPyStudy\Data\ArcpyBook\Ch2\Crime_Ch2_new_ExportReport.pdf") # print("Export Done") # import arcpy.mapping as mapping
def mappingProcess(datetime, province, target_area, density_class=None, day_class=10, out_path=None, out_type= "png"): # todo.控制densityClass和dayClass最多为14 cwd = os.getcwd() infeature = ''.join([cwd, u"/data/LightningBulletin.gdb/", target_area]) mxd_density_path = ''.join([cwd, u"/data/LightningBulletin.gdb/", target_area, u"闪电密度空间分布模板.mxd"]) mxd_day_path = ''.join([cwd, u"/data/LightningBulletin.gdb/", target_area, u"地闪雷暴日空间分布模板.mxd"]) workspace = ''.join([cwd, u"/temp/", province, '/', datetime, '/', target_area, '.gdb']) arcpy.env.workspace = workspace arcpy.env.overwriteOutput = True # *****处理地闪密度地图文档******* mxd = mapping.MapDocument(mxd_density_path) mask_lyr = mapping.ListLayers(mxd)[2] target_lyr = mapping.ListLayers(mxd)[3] mask_lyr.replaceDataSource(workspace, "FILEGDB_WORKSPACE", "densityMask") target_lyr.replaceDataSource(workspace, "FILEGDB_WORKSPACE", "lightningDensity") # 修改图例 # 计算数据分割值和不显示值 extract = ExtractByMask("lightningDensity", infeature) raster = Raster("lightningDensity") class_break_values, density_class = densityLegendLabel(extract.minimum / 100, extract.maximum / 100, density_class) excluded_values = ''.join([str(round(raster.minimum - 0.5, 2)), "-", str(round(extract.minimum - 0.5, 2)), ";", str(round(extract.maximum + 0.5, 2)), "-", str(round(raster.maximum + 0.5, 2))]) sym = target_lyr.symbology sym.excludedValues = excluded_values sym.classBreakValues = [x * 100 for x in class_break_values] # 更改标题和图例 layout_items = mapping.ListLayoutElements(mxd, "TEXT_ELEMENT") layout_items[-1].text = ''.join([datetime, target_area, u"闪电密度空间分布"]) # title标题 layout_items[-2].text = ''.join([target_area, u"气象局制"]) # 底注 density_class = class_break_values.__len__() - 1 class_break_values = [str(x) for x in class_break_values] # TODO 将position参数放到设置文件里,或者自动处理 position = {u"绍兴市": (1.0436, 1.6639, 0.9859272727272728), u"嵊州市": (1.1138, 1.2614, 0.9869090909090698), u"上虞区": (1.1372, 1.1617, 0.9862375000000156), u"诸暨市": (1.1138, 1.2614, 0.9869090909090698), u"柯桥区": (1.1372, 1.1617, 0.9862375000000156), u"新昌县": (1.1138, 1.2614, 0.9869090909090698), u"新乡市": (1.0436, 1.6639, 0.9859272727272728)} Y, Xstart, gap = position[target_area] for i in xrange(density_class + 1): layout_items[i].text = class_break_values[i] layout_items[i].elementPositionY = Y layout_items[i].elementPositionX = Xstart + gap * i for i in xrange(density_class + 1, 15): # 最多14类,15个标签 layout_items[i].elementPositionX = -20 mxd.save() if not out_path: out_path = workspace out_name = os.path.join(out_path, ''.join([datetime, target_area, u"闪电密度空间分布"])) out_type = out_type.lower() if out_type in ["jpg", 'gpeg']: mapping.ExportToJPEG(mxd, out_name, resolution=200) elif out_type == "png": mapping.ExportToPNG(mxd, out_name, resolution=200) elif out_type == "pdf": mapping.ExportToPDF(mxd, out_name) elif out_type == "bmp": mapping.ExportToBMP(mxd, out_name, resolution=200) else: mapping.ExportToTIFF(mxd, out_name, resolution=200) # *****处理雷暴日地图文档******* mxd = mapping.MapDocument(mxd_day_path) mask_lyr = mapping.ListLayers(mxd)[2] target_lyr = mapping.ListLayers(mxd)[3] mask_lyr.replaceDataSource(workspace, "FILEGDB_WORKSPACE", "dayMask") target_lyr.replaceDataSource(workspace, "FILEGDB_WORKSPACE", "lightningDay") # 修改图例 # 计算数据分割值和不显示值 extract = ExtractByMask("lightningDay", infeature) raster = Raster("lightningDay") start = floor(extract.minimum) end = ceil(extract.maximum) class_break_values, day_class = dayLegendLabel(start, end, day_class) excluded_values = ''.join([str(round(raster.minimum - 0.5, 2)), "-", str(round(extract.minimum - 0.5, 2)), ";", str(round(extract.maximum + 0.5, 2)), "-", str(round(raster.maximum + 0.5, 2))]) sym = target_lyr.symbology sym.excludedValues = excluded_values sym.classBreakValues = class_break_values # 更改标题和图例 layout_items = mapping.ListLayoutElements(mxd, "TEXT_ELEMENT") layout_items[-1].text = ''.join([datetime, target_area, u"地闪雷暴日空间分布"]) layout_items[-2].text = ''.join([target_area, u"气象局制"]) # 底注 Y, Xstart, gap = position[target_area] for i in xrange(day_class + 1): layout_items[i].text = class_break_values[i] layout_items[i].elementPositionY = Y layout_items[i].elementPositionX = Xstart + gap * i for i in xrange(day_class + 1, 15): # 最多14类,15个标签 layout_items[i].elementPositionX = -20 mxd.save() out_name = os.path.join(out_path, ''.join([datetime, target_area, u"地闪雷暴日空间分布"])) out_type = out_type.lower() if out_type in ["jpg", 'gpeg']: mapping.ExportToJPEG(mxd, out_name, resolution=200) elif out_type == "png": mapping.ExportToPNG(mxd, out_name, resolution=200) elif out_type == "pdf": mapping.ExportToPDF(mxd, out_name) elif out_type == "bmp": mapping.ExportToBMP(mxd, out_name, resolution=200) else: mapping.ExportToTIFF(mxd, out_name, resolution=200)
import arcpy.mapping as mapping mxd = mapping.MapDocument("CURRENT") for df in mapping.ListDataFrames(mxd): if df.name == "Microlocalizacion": mapping.ExportToJPEG( mxd, r'C:\EsriTraining\PythEveryone\PythonInArcGIS\Micro.jpg', df, world_file=True) print "script complete!"
def makeMaps(rast, name): fullrast = os.path.join(rootdir, rast) if os.path.isfile(fullrast): #cropAccList = [("alf", "Alfalfa"), ("dry", "Beans"), ("cot", "Cotton"), ("cor", "Corn"), # ("pea", "Peas"), ("sil", "Corn Silage"), ("soy", "Soybeans"), ("wht", "Wheat")] #yieldStabList = [("level", "Yield Level"), ("_stab", "Yield Stability"), ("t_var", "Temporal Variance")] mxd = mapping.MapDocument(MXD) # get empty arcgis file df = mapping.ListDataFrames(mxd, "*")[0] for elm in mapping.ListLayoutElements( mxd, "TEXT_ELEMENT" ): # loop through the elements in the mxd and set them print "element: ", elm.name if elm.name == "Title": elm.text = "SALUS simulated VARIABLE, " + SC #if elm.name == "Unstable": # elm.elementPositionX = -5 #if elm.name == "total_area": # elm.elementPositionX = -5 layer = mapping.Layer(fullrast) # add the raster layer to the mxd mapping.AddLayer(df, layer, "TOP") arcpy.RefreshTOC() # refresh arcpy.RefreshActiveView() # Load the symbology layer (from a file or create one from the raster on the fly) #lyrname = SC + "_" + name ## Execute MakeFeatureLayer (save raster to lyr symbology file) ##arcpy.MakeRasterLayer_management(rast, lyrname, rootdir) #outlyr = rast.replace(".tif",".tif.lyr") outlyr = "mi_SC3_endvalue.tif.lyr" outlyr = os.path.join(lyr_folder, outlyr) sym_lay = mapping.Layer( outlyr ) # lyrname (using lines above) # or I can skip the line above and call the full path name (if lyr file is already made) lay_name = "Variable (units)" #mapping.AddLayer(df, layer, "TOP") updateLayer = mapping.ListLayers(mxd, "", df)[0] update_layer(df, updateLayer, sym_lay, True) apply_sym( updateLayer, sym_lay ) # added symbology_only = True so that the layer becomes classified (symbology)?? updateLayer.name = lay_name print "Added layer." #style_stab = mapping.ListStyleItems("USER_STYLE", "Legend Items")[0] legend = mapping.ListLayoutElements(mxd, "LEGEND_ELEMENT")[ 0] # updates all legend items to the chosen style for lyr in legend.listLegendItemLayers(): #[:3]: # legend.updateItem(lyr, style_stab) print "in legend: ", lyr.name if "States" in lyr.name or "Counties" in lyr.name: print "states is in legend" legend.removeItem(lyr) ############## endvarlist = ["avgGWAD", "avgCWAD"] for var in endvarlist: name = var + "_" + name for lyr in mapping.ListLayers( mxd, "", df)[:-1]: # -1 to avoid boundary layer lyr.visible = True print "layer name: ", lyr.name # change the symbology value field if lyr.symbologyType == "RASTER_CLASSIFIED": #, then create a variable reference to the RasterClassifiedSymbology class for that layer (lyrSymbolClass = lyr.symbology) print "RASTER IS CLASSIFIED" lyr.symbology.valueField = var # first value is the minimum #lyr.symbology.classBreakValues = [1, 60, 118, 165, 255] # one less label than the classBreakValues #lyr.symbology.classBreakLabels = ["1 to 60", "61 to 118", # "119 to 165", "166 to 255"] #lyr.symbology.classBreakDescriptions = ["Class A", "Class B", # "Class C", "Class D"] # lyr.symbology.excludedValues = '0' #name_temp = lyr.name #name = "{}.jpg".format(name_temp.replace(" ", "_")) arcpy.RefreshTOC() # refresh the TOC and active view arcpy.RefreshActiveView() outjpeg = os.path.join(outdir, name) mapping.ExportToJPEG(mxd, outjpeg, "PAGE_LAYOUT", resolution=300, jpeg_quality=100) #export to jpeg lyr.visible = False # switch off layer arcpy.RefreshTOC() # refresh again arcpy.RefreshActiveView() print "Created jpeg's of layers." # Save a copy of the mxd with the layer in it to the MXDs directory new_mxd_name = name + ".mxd" new_mxd = os.path.join(newMXDdir, new_mxd_name) arcpy.RefreshTOC() # refresh again arcpy.RefreshActiveView() mxd.saveACopy(new_mxd) ################## # Save the mapp and its data to a single compressed .mpkx file #MPK_name = name + ".mpk" #MPK_name = os.path.join(MPKdir, MPK_name) #print new_mxd #print MPK_name #arcpy.PackageMap_management(new_mxd, MPK_name, "PRESERVE", "CONVERT_ARCSDE", "#", "ALL") # crashes the script :( del mxd del df print "Done with ", rast print arcpy.Delete_management("in_memory") else: print "This raster does not exist:", fullrast
# -*- coding: utf-8 -*- """ Created on Tue Jul 21 14:28:28 2020 @author: Lina """ import arcpy, os from arcpy import mapping as m arcpy.env.overwriteOutput = True mapPath = r'C:\Users\Lina\Google Drive\Leo\2_SIG\MXD\PruebaBatchMapas\Prueba.mxd' outpath = r'C:\Users\Lina\Google Drive\Leo\2_SIG\MXD\PruebaBatchMapas\Exports' mxd = m.MapDocument(mapPath) df = m.ListDataFrames(mxd)[0] # Loop through layers for lyr in m.ListLayers(mxd, 'GMRT3_*'): lyr.visible = True #lyr.showLabels = True # I'm assuming this is where you have the properties? jpg = os.path.join(outpath, lyr.name + '.jpg') m.ExportToJPEG(mxd, jpg) #print('Exported %s') %jpg lyr.visible = False del mxd
import arcpy.mapping as mapping mxd = mapping.MapDocument("CURRENT") for df in mapping.ListDataFrames(mxd): if df.name == "New_Micro": mapping.ExportToJPEG( mxd, r'C:\EsriTraining\PythEveryone\PythonInArcGIS\New_Micro.jpg', df) print "Script complete!"
def CreateMXD(srcMXD, srcSHPDirs, targetDir, srcLyrDirs, srcGeo, srcStyleName, srcXlsxWB, srcSubjects, srcLogo): mxd = amp.MapDocument(srcMXD) mxdDF0 = amp.ListDataFrames(mxd, "Main")[0] mxdDF1 = amp.ListDataFrames(mxd, "Index")[0] prCode = srcGeo['prCode'] coCode = srcGeo['coCode'] ciCode = srcGeo['ciCode'] shpCity = srcSHPDirs['shpCity'] shpCounty = srcSHPDirs['shpCounty'] shpCounties = srcSHPDirs['shpCounties'] shpRegion = srcSHPDirs['shpRegion'] lyrCity = srcLyrDirs['lyrCity'] lyrCounty = srcLyrDirs['lyrCounty'] lyrCounties = srcLyrDirs['lyrCounties'] srcLyrCity = amp.Layer(lyrCity) srcLyrCounty = amp.Layer(lyrCounty) srcLyrCounties = amp.Layer(lyrCounties) mxdLayer00 = amp.Layer(shpRegion) mxdLayer10 = amp.Layer(shpCity) mxdLayer11 = amp.Layer(shpCounty) mxdLayer12 = amp.Layer(shpCounties) amp.AddLayer(mxdDF0, mxdLayer00, "TOP") amp.AddLayer(mxdDF1, mxdLayer12, "TOP") amp.AddLayer(mxdDF1, mxdLayer11, "TOP") amp.AddLayer(mxdDF1, mxdLayer10, "TOP") addLayer = amp.ListLayers(mxd, "", mxdDF1)[0] amp.UpdateLayer(mxdDF0, addLayer, srcLyrCity, True) addLayer = amp.ListLayers(mxd, "", mxdDF1)[1] amp.UpdateLayer(mxdDF0, addLayer, srcLyrCounty, True) addLayer = amp.ListLayers(mxd, "", mxdDF1)[2] amp.UpdateLayer(mxdDF0, addLayer, srcLyrCounties, True) addLayer = amp.ListLayers(mxd, "", mxdDF0)[0] fields = arcpy.ListFields(shpRegion) for field in fields: fieldName = field.name fieldCategory = fieldName[0:3] if fieldCategory in srcSubjects: lyrRegion = srcLyrDirs['lyrRegion'][fieldCategory] srcLyrRegion = amp.Layer(lyrRegion) amp.UpdateLayer(mxdDF0, addLayer, srcLyrRegion, True) if addLayer.supports("LABELCLASSES"): for labelClass in addLayer.labelClasses: labelClass.showClassLabels = True labelClass.expression = "\"<CLR red = '0' green = '0' blue = '0'><FNT size = '10' name = 'B Yekan'>\" & [areaCode] & \"</FNT></CLR>\"" addLayer.showLabels = True arcpy.RefreshActiveView() if addLayer.symbologyType == 'GRADUATED_COLORS': addLayer.symbology.valueField = fieldName labels = addLayer.symbology.classBreakLabels try: addLayer.symbology.classBreakLabels = createRanges(labels) except: print('Error in Symbology | %s' % fieldName) style0 = amp.ListStyleItems("USER_STYLE", "Legend Items", srcStyleName)[0] mxd_legend = amp.ListLayoutElements(mxd, "LEGEND_ELEMENT")[0] mxd_legend.title = "" mxd_legend.updateItem(addLayer, style0) for element in amp.ListLayoutElements(mxd, "PICTURE_ELEMENT"): elementName = element.name if elementName == 'Logo': element.sourceImage = srcLogo variableKeys = srcXlsxWB.sheet_by_index(0).row(0) colId = findInCellArray(variableKeys, fieldName) mapTitles = srcXlsxWB.sheet_by_index(0).cell_value(1, colId) for sheet in srcXlsxWB.sheets(): sheetName = sheet.name if sheetName == 'total': countryValue = sheet.cell_value(2, colId) elif sheetName == 'province': featureKeys = sheet.col(0) rowId = findInCellArray(featureKeys, makeStandard(prCode)) provinceName = sheet.cell_value(rowId, 1) provinceValue = sheet.cell_value(rowId, colId) elif sheetName == 'county': featureKeys = sheet.col(0) rowId = findInCellArray(featureKeys, makeStandard(coCode)) countyName = sheet.cell_value(rowId, 1) countyValue = sheet.cell_value(rowId, colId) elif sheetName == 'city': featureKeys = sheet.col(0) rowId = findInCellArray(featureKeys, makeStandard(ciCode)) cityName = sheet.cell_value(rowId, 1) cityName0 = cityName[0: len(cityName) - 1] cityName1 = cityName[len(cityName) - 1] if (isStrNumber(cityName1)): cityName = Utf8ToUnicode('منطقه ') + cityName1 + Utf8ToUnicode('شهر ') + cityName0 else: cityName = Utf8ToUnicode('شهر ') + cityName cityValue = sheet.cell_value(rowId, colId) elif sheetName == 'unit': unitText = sheet.cell_value(2, colId) for element in amp.ListLayoutElements(mxd, "TEXT_ELEMENT"): elementName = element.name if elementName == 'elLegend': mapTitles = maskTitle(" ".join(mapTitles.split())) defWidth = 8 element.fontSize = 16 element.text = mapTitles if element.elementWidth >= defWidth: words = mapTitles.split(' ') lines = [] line = [] tmp = '' itr = 0 while itr < len(words): word = words[itr] itr += 1 tmp += word + ' ' element.text = tmp line.append(word) if element.elementWidth >= defWidth: line.pop() lines.append(line) line = [] tmp = '' itr = itr - 1 if itr == len(words): count = 0 for l in lines: count += len(l) if count < len(words): lines.append(line) mapTitlesNew = '' for jj in range(0, len(lines)): lineStr = " ".join(lines[jj]) mapTitlesNew += lineStr if jj < len(lines) - 1: mapTitlesNew += "\n" element.text = mapTitlesNew elif elementName == 'elUnit' or elementName == 'elUnit2': element.text = unitText elif elementName == 'countryValue': element.text = round(countryValue,2) elif elementName == 'elProvinceTitle': element.text = Utf8ToUnicode('مناطق شهری استان ') + provinceName elif elementName == 'provinceValue': element.text = round(provinceValue,2) elif elementName == 'elCountyTitle': element.text = Utf8ToUnicode('مناطق شهری شهرستان ') + countyName elif elementName == 'countyValue': element.text = round(countyValue,2) elif elementName == 'elCityTitle': element.text = cityName elif elementName == 'cityValue': element.text = round(cityValue,2) try: mxd_name = targetDir['mxd'] + "//" + fieldName + ".mxd" mxd.saveACopy(mxd_name) except arcpy.ExecuteError: print(arcpy.GetMessages()) try: mxd_jpg_name = targetDir['jpg'] + fieldName + ".jpg" amp.ExportToJPEG(mxd, mxd_jpg_name, resolution=300) # multiprocessing.freeze_support() # p = multiprocessing.Process(target=test, args=(mxd.__getattribute__('filePath'), mxd_jpg_name)) # p.start() # p.join() except arcpy.ExecuteError: print(arcpy.GetMessages())