Esempio n. 1
0
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 doVariosTematicos(self):
        '''
        @param: self
        @brief: Realiza el mapa con varios temáticos
        @return: None
        '''
        if self.mode == 1: self.setTwoDataFrameMode()

        layer_df1, layer_df2 = self.layers

        fields = [
            self.combo_comp_t1.currentText(),
            self.combo_comp_t2.currentText()
        ]

        filename = path.join(
            self.export_folder,
            '{}_vt_{}_{}_{}.pdf'.format(self.title, '_'.join(self.append_info),
                                        *fields))

        layer_df1.symbology.valueField = fields[0]
        layer_df2.symbology.valueField = fields[1]
        print 'VT Break Values', layer_df1.symbology.classBreakValues
        print 'VT Break Values', layer_df2.symbology.classBreakValues
        #layer_df1.symbology.classBreakValues = self.normalizeBreakValues(layer_df1.symbology.classBreakValues)
        #layer_df2.symbology.classBreakValues = self.normalizeBreakValues(layer_df2.symbology.classBreakValues)
        mapping.ExportToPDF(self.mxd, filename)
    def doTematicoSimple(self):
        '''
        @param: self
        @brief: Realiza el mapa temático simple
        @return: None
        '''

        # Si está en modo (2 Layouts), pasamos a modo (1 Layout)
        if self.mode == 2: self.setOneDataFrameMode()

        layer_df1, _ = self.layers

        # Hacemos que el DF ocupe todo el ancho si no hay leyenda
        if not self.check_legend.isChecked():
            self.dataframe1.elementWidth += self.legend_df1.elementWidth

        field = self.combo_ts.currentText()
        filename = path.join(
            self.export_folder,
            '{}_ts_{}_{}.pdf'.format(self.title, '_'.join(self.append_info),
                                     field))

        layer_df1.symbology.valueField = field
        print 'TS Break Values', layer_df1.symbology.classBreakValues

        #layer_df1.symbology.classBreakValues = self.normalizeBreakValues(layer_df1.symbology.classBreakValues)
        #self.GRADUATED_COLORS.symbology.valueField = field
        #arcpy.ApplySymbologyFromLayer_management(layer_df1, self.GRADUATED_COLORS)

        mapping.ExportToPDF(self.mxd, filename)

        # Volvemos a hacer que el dataframe ocupe el ancho original
        # si no hay leyenda
        if not self.check_legend.isChecked():
            self.dataframe1.elementWidth -= self.legend_df1.elementWidth
Esempio n. 4
0
def export_maps(mxd, btn_layer, btn_export_pdf, btn_export_png):
    map_name = str(btn_layer.objectName())[6:]
    if btn_export_png.isChecked() == True:
        #print btn_layer.text(), ' Print PNG'
        map.ExportToPNG(mxd, map_name+".png", resolution=300, \
                        transparent_color='255, 255, 255')
    if btn_export_pdf.isChecked() == True:
        #print btn_layer.text(), ' Print PDF'
        map.ExportToPDF(mxd, map_name+".pdf" )
Esempio n. 5
0
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 doNormalizacion(self):
        '''
        @param: self
        @brief: Realiza el mapa de normalización
        @return: None
        '''

        if self.mode == 2: self.setOneDataFrameMode()

        layer_df1, _ = self.layers

        # Hacemos que el DF ocupe todo el ancho si no hay leyenda
        if not self.check_legend.isChecked():
            self.dataframe1.elementWidth += self.legend_df1.elementWidth

        fields = [
            self.combo_norm_c1.currentText(),
            self.combo_norm_c2.currentText()
        ]

        filename = path.join(
            self.export_folder,
            '{}_norm_{}_{}_{}.pdf'.format(self.title,
                                          '_'.join(self.append_info), *fields))

        layer_df1.symbology.valueField = fields[0]
        layer_df1.symbology.normalization = fields[1]
        #layer_df1.symbology.numClasses = 5
        print 'NORM Break Values', layer_df1.symbology.classBreakValues
        #layer_df1.symbology.classBreakValues = self.normalizeBreakValues(layer_df1.symbology.classBreakValues)
        mapping.ExportToPDF(self.mxd, filename)

        # Ponemos normalización igual a None
        # Así no afectará a próximos mapas
        layer_df1.symbology.normalization = None

        # Volvemos a hacer que el dataframe ocupe el ancho original
        # si no hay leyenda
        if not self.check_legend.isChecked():
            self.dataframe1.elementWidth -= self.legend_df1.elementWidth
Esempio n. 7
0
df = map.ListDataFrames(mxd)[0] #acceso al primer mapa de la lista (dataframe)
#Acceso a la primera y ultima capa de la lista
lista_capas = map.ListLayers (mxd,"",df) #acceso a la lista de capas
n = len(lista_capas) #numero de capas
primera = lista_capas[0] #primera capa (la de arriba)
ultima = lista_capas[n-1] #ultima capa (la de abajo)

#Desplazamiento de la capa
map.MoveLayer(df,primera,ultima,'BEFORE')

#Refresco de la vista y de la TOC (solo si mxd = 'CURRENT'
arcpy.RefreshActiveView()
arcpy.RefreshTOC()

#Exportar mapa a pdf
map.ExportToPDF(mxd, "C:/Projecto/Output/mapa.pdf")

#liberacion de memoria
del mxd, df, primera, ultima

#-------------------------------------------------------------------------------
# DESCRIBE LAYERS
#-------------------------------------------------------------------------------
import arcpy
import arcpy.mapping as map #cambio el nombre del modulo

#Definicion de variables
ruta_mxd = r'C:\asignaturas\sig1\2013-2014\cuatrimestre B\teoria\MT2\2_acceso_mapa\castilla_leon.mxd'
mxd = map.MapDocument(ruta_mxd) #acceso al proyecto
df = map.ListDataFrames(mxd)[0] #acceso al primer mapa de la lista (dataframe)
#Acceso a la primera y ultima capa de la lista
    '48': 'Edmonton',
    '59': 'Vancouver',
    '60': 'Vancouver',
    '61': 'Edmonton',
    '62': 'Edmonton'
}  # Parses province code into destination city
map_count = 0
for mxd_name in metrics_df['MXD_NAME']:  # Loop over the True MXD's and

    pdf_name = mxd_name.split('.')[0]  # Get the base name for the pdf
    prcode = pdf_name.split('-')[4][:2]  # Determine Province code

    print 'PDFing {}'.format(mxd_name)

    if '_CSD202103.mxd' not in mxd_name:
        mxd_name = mxd_name.split(
            '.'
        )[0] + '_CSD202103.mxd'  # this is here because I made a mistake not adding this to the metrics doc

    mxd_path = os.path.join(working_directory,
                            mxd_name)  # make path to mxd from components
    mxd = mp.MapDocument(mxd_path)  # Make mxd object

    pdf_path = os.path.join(out_dir, destination_dict[prcode],
                            pdf_name + '.pdf')  # Build PDF path
    mp.ExportToPDF(mxd, pdf_path)  # Export map as PDF
    map_count += 1

print 'Total # of maps updated ' + str(map_count)
print 'DONE!'
Esempio n. 9
0
        if graphic.name == "txt_vode":
            graphic.text = str(cod)
        if graphic.name == "txt_area":
            graphic.text = str('% .2f' % area) + " KM2"
        if graphic.name == "txt_perimeter":
            graphic.text = str('% .2f' % perimeter) + " KM"
    graphic_list2 = map.ListLayoutElements(mxd, "GRAPHIC_ELEMENT")
    graph_width1a = 15
    graph_width1b = 0
    graph_width2a = 15
    graph_width2b = 0
    ##    for graph in graphic_list2:
    ##        if graphic.name == "graph1_pop1":
    ##            graphic.width =

    map.ExportToPDF(mxd,
                    "C:\Users\laboratorios\ELVLC\session6" + name + ".pdf")
    row = cur.next()

#-------------------------------------------------------------------------------
# GRAPHIC ELEMENT
#-------------------------------------------------------------------------------
import arcpy
import arcpy.mapping as map

path = r"C:\Users\laboratorios\ELVLC\session6\session6.mxd"
mxd = map.MapDocument(path)

graphic_list = map.ListLayoutElements(mxd, "TEXT_ELEMENT")

for graphic in graphic_list:
    ##    if graphic.name !="":
Esempio n. 10
0
    print(el.name)

# 4 更新布局元素的属性
import arcpy.mapping as mapping
mxd = mapping.MapDocument(
    r"E:\ArcPyStudy\Data\ArcpyBook\Ch2\Crime_Ch2_new.mxd")
elLeg = mapping.ListLayoutElements(mxd, "LEGEND_ELEMENT", "*Crime*")[0]
elLeg.title = "Crime by School District"
for item in elLeg.listLegendItemLayers():
    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
Esempio n. 11
0
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)
               
                string =str(vv) if isinstance(vv,int) else vv 
              

                cell_text_clone.text = add_style(styleDict,key,string.strip(),fontsize) 
                cell_text_clone.elementPositionX = cell_coords[i][ii][0]
                cell_text_clone.elementPositionY = cell_coords[i][ii][1]
                
            

        #exporting map
        arcpy.RefreshActiveView()
        export_dir = r"G:\GSC\Projects\BisWorking\kitchen\IndustrialLands\pdf"
        pdf_name =mxd.title+"_"+ lga+".pdf"
        pdf_path = os.path.join(export_dir,pdf_name)
        #remove if exists
        if os.path.exists(pdf_path):
            os.remove(pdf_path)
        mapping.ExportToPDF(mxd, pdf_path, resolution = 300)
        print "Map {} Exported!".format(pdf_name)
        delete_clone_elements(mxd)
    print "Completed!"


        
        

        


Esempio n. 13
0
# Author:      Eric
#
# Created:     05/04/2018
# Copyright:   (c) Eric 2018
# Licence:     <your licence>
#-------------------------------------------------------------------------------

#import module
import arcpy.mapping as mapping, os

#reference currently active map document
mxd = mapping.MapDocument("CURRENT")

# retrieve the crime data frame
df = mapping.ListDataFrames(mxd, "Crime")[0]

# generate DataFrameTime object
dft = df.time

# set current time property to start time property
dft.currentTime = dft.startTime

# start a while loop while current time is less than or equal to end time
while dft.currentTime <= dft.endTime:
    # create a file for each PDF to be created
    # and reset current time property
    fileName = str(dft.currentTime).split(" ")[0] + ".pdf"

    mapping.ExportToPDF(mxd, os.path.join(r"c:\ArcPyBook\Ch2", fileName),df)
    print("Exported " + fileName)
    dft.currentTime = df.time.currentTime + dft.timeStepInterval
Esempio n. 14
0
#Original
strInFileDirectory = raw_input("In Directory: ")
strOutFileDirectory = raw_input("Out Directory: ")
count = 0

for (dirname, dirs, files) in os.walk(strInFileDirectory):
    # print dirname
    # print dirs
    # print files
    # print "\n"
    # print dirname
    for filename in files:
        if filename.endswith(".mxd"):  # & count <= 1
            #Needed to first rename the files to be distinct by adding the data date. Did this just once.
            # strNewName = dirname[-8:] + filename
            # os.rename(os.path.join(dirname,filename),os.path.join(dirname,strNewName))

            strMXDPath = os.path.join(dirname, filename)
            mapDoc = mapping.MapDocument(strMXDPath)
            strRootMXDName = filename[0:-4] + ".pdf"
            strNewPdfPath = os.path.join(strOutFileDirectory, strRootMXDName)
            try:
                mapping.ExportToPDF(map_document=mapDoc, out_pdf=strNewPdfPath)
            except:
                print "problem exporting to pdf"
            count += 1
            print "MXD printed: {}, count={}".format(filename, count)
            del mapDoc
print "All Done"
sys.exit()
Esempio n. 15
0
#feature iteration (cursor)
cursor = arcpy.SearchCursor(layer, query)
name_mun = ''
population = 0
for row in cursor:
    name_mun = row.getValue('NOMBRE')
    population = row.getValue('POB95')
#template processing
for graphic in map.ListLayoutElements(mxd):
    if graphic.name == 'txt_name':
        graphic.text = name_mun
    if graphic.name == 'txt_population':
        graphic.text = population
#export result to pdf file
map.ExportToPDF(
    mxd,
    r'E:\asignaturas\master\DAS\2016-2017\temario_ingles\session4\theory\map.pdf'
)

#-------------------------------------------------------------------------------
# DEM MANAGEMENT
#-------------------------------------------------------------------------------
import arcpy

arcpy.env.overwriteOutput = True
#workspace
input_folder = r"C:\DAS\DATA\64032"

#output_folder
output_folder = r"C:\DAS\DATA\64032\results"
spot = input_folder + "\\64032puntos_cota.shp ELEVACI?N <none> masspoints false"
contours = input_folder + "\\64032curvas_nivel.shp ELEVACI?N <none> softline false"
Esempio n. 16
0
                            legend.elementPositionY = 4.9
                            for item in legend.listLegendItemLayers():
                                legend.updateItem(item,
                                                  styleItem,
                                                  show_feature_count=True)
##                                    if item.name == str(Cfc):
##                                       legend.removeItem(item)
##                                    if item.name == str(Officialfc) or item.name == str(RMSHDfc):
##                                        legend.updateItem(item, show_feature_count = True)

#Refresh TOC and ActiveView
                            arcpy.RefreshActiveView()
                            arcpy.RefreshTOC()

                            map.ExportToPDF(
                                mxd, r"C:/gc_work/evl/Outputs/" + floodmodel +
                                "_" + name + ".pdf")

                            map.RemoveLayer(df, InputBuildingLayer_temp)
                            map.RemoveLayer(df, InputRMSHDFishnetLayer_temp)
                            map.RemoveLayer(df, InputOfficialFishnetLayer_temp)
                            map.RemoveLayer(df, InputCityLayer_temp)
                            map.RemoveLayer(df, BuildingLayer)
                            map.RemoveLayer(df, RMSHDFishnetLayer)
                            map.RemoveLayer(df, OfficialFishnetLayer)
                            map.RemoveLayer(df, CityLayer)

                            ##                    mxd.save()

                            del InputBuildingLayer_temp, InputRMSHDFishnetLayer_temp, InputOfficialFishnetLayer_temp, InputCityLayer_temp
                            del BuildingLayer, RMSHDFishnetLayer, OfficialFishnetLayer, CityLayer
Esempio n. 17
0
import arcpy.mapping as mapping
mxd = mapping.MapDocument("CURRENT")
for df in mapping.ListDataFrames(mxd):
    if df.name == "New_Micro":
        mapping.ExportToPDF(
            mxd, r"C:\\EsriTraining\\PythEveryone\\PythonInArcGIS\\New.pdf",
            df)
        print "list"
Esempio n. 18
0
import arcpy.mapping as mapping
mxd = mapping.MapDocument("CURRENT")
mapping.ExportToPDF(
    mxd, r'C:\EsriTraining\PythEveryone\PythonInArcGIS\Map_PageLayout.pdf')