Example #1
0
    def to_package(self, output_file, summary, tags, **kwargs):
        """
			Though it's not normally a mapping method, packaging concepts need translation between the two versions, so
			we've included to_package for maps and projects. In ArcGIS Pro, project.to_package will create a Project Package
			and map.to_package will create a map package. In ArcMap, both will create a map package. Extra **kwargs beyond
			output path are only passed through to Pro Package command, not to map packages. To pass kwargs through to a map
			package, use a map object's to_package method.
		:param output_file: the path to output the package to
		:param kwargs: dictionary of kwargs to pass through to project packaging in Pro.
		:return: None
		"""

        log.warning("Warning: Saving project to export package")
        self.save()

        if PRO:
            arcpy.PackageProject_management(self.path,
                                            output_file,
                                            summary=summary,
                                            tags=tags,
                                            **kwargs)
        else:
            arcpy.PackageMap_management(self.path,
                                        output_file,
                                        summary=summary,
                                        tags=tags)
Example #2
0
def create_mpk(data_location, mxd, additional_files=None):
    """Creates a map package (.mpk) for all the datasets in the data location.
    :param data_location: location of data to be packaged
    :param mxd: existing map document template (mxd path)
    :param additional_files: list of additional files to include in the package
    """
    import arcpy
    arcpy.PackageMap_management(mxd, mxd.replace('.mxd', '.mpk'),
                                'PRESERVE', version='10', additional_files=additional_files)
    make_thumbnail(mxd, os.path.join(os.path.dirname(data_location), '_thumb.png'))
Example #3
0
    def to_package(self, output_file, **kwargs):
        """
			Though it's not normally a mapping method, packaging concepts need translation between the two versions, so
			we've included to_package for maps and projects. In ArcGIS Pro, project.to_package will create a Project Package
			and map.to_package will create a map package. In ArcMap, both will create a map package. Calling to_package on the map
			will pass through all kwargs to map packaging because the signatures are the same between ArcMap and ArcGIS Pro.
			Sending kwargs to project.to_package will only send to project package since they differ.

		:param output_file:
		:param kwargs:
		:return:
		"""

        log.warning("Warning: Saving map to export package")
        self.project.save()

        if PRO:
            arcpy.PackageMap_management(self.map_object, output_file, **kwargs)
        else:
            arcpy.PackageMap_management(self.project.path, output_file,
                                        **kwargs)
Example #4
0
def mpkExport(arguments):
    """
    Goes through the list of mxds in the given directory and tries to export them as mpks.
    Needs:
        arguments: the list of arguments from the parser in main()
    """
    workspace = arguments.inDir
    output = arguments.outDir
    logDir = arguments.logDir
    logName = arguments.logName
    error_count = 0
    # Set environment settings
    arcpy.env.overwriteOutput = True
    arcpy.env.workspace = workspace
    mxdlist = arcpy.ListFiles("*.mxd")
    # Create a logfile
    log = createLogfile(logDir, logName)

    if len(mxdlist) < 1:
        error_count -= 1
    else:
        # Loop through the workspace, find all the mxds and create a map package using the same name as the mxd
        for mxd in mxdlist:
            print("Packaging " + mxd)
            outPath = output + '\\' + os.path.splitext(mxd)[0]
            try:
                arcpy.PackageMap_management(mxd, outPath + '.mpk', "PRESERVE",
                                            "CONVERT_ARCSDE", "#", "ALL",
                                            "RUNTIME")
                print("SUCCESS: " + mxd + " processed successfully.")
                # if a packaging folder was created, it will be removed
                if os.path.exists(outPath):
                    try:
                        shutil.rmtree(outPath, onerror=remove_readonly)
                    except Exception as e:
                        error_count += 1
                        writeLog(log, e, error_count, mxd)
                        print(
                            "Removal of package directory " + outPath +
                            " failed. Consider running the script with administrator permissions."
                        )
            except Exception as e:
                error_count += 1
                writeLog(log, e, error_count, mxd)
                print("ERROR while processing " + mxd)

    # close the Logfile
    closeLog(log, error_count)
Resumen = arcpy.GetParameterAsText(3)  #Variable para el resumen
Descripcion = arcpy.GetParameterAsText(4)  #Variable para la descripciĆ³n
#Etiqueta = arcpy.GetParameterAsText(5) #Variable para las etiquetas. Las etiquetas se separan por comas (,)

for dirpath, subdirs, files in os.walk(source):
    for x in files:
        if x.endswith(".mxd"):
            mxdList.append(os.path.join(dirpath, x))

arcpy.AddMessage("\n")
arcpy.AddMessage("Procesando: ")

for mxd in mxdList:
    mpk = mxd.replace(".mxd", ".mpk")
    MXDpath = mxd

    mapdoc = arcpy.mapping.MapDocument(MXDpath)
    MPKpath = mpk

    if Booleano == "true":
        mapdoc.title = Titulo  #mapdoc.filePath Cambiar despues a nombre del MXD
        mapdoc.summary = Resumen
        mapdoc.description = Descripcion
        mapdoc.tags = "Mapas"
        mapdoc.save()

    arcpy.PackageMap_management(MXDpath, MPKpath)
    arcpy.AddMessage("El archivo MXD fue exportado en:" + MPKpath)

    del mapdoc
Example #6
0
def export_map_document(product_location,
                        mxd,
                        map_doc_name,
                        data_frame,
                        outputdirectory,
                        export_type,
                        production_xml=None):
    """Exports MXD to chosen file type"""

    try:
        export = export_type.upper()
        product = arcpy.ProductInfo()
        arcpy.AddMessage("Product: " + product)

        if product == 'ArcServer':
            filename_prefixe = "_ags_"
        else:
            filename_prefixe = ""

        if export == "PDF":
            filename = filename_prefixe + map_doc_name + ".pdf"
            outfile = os.path.join(outputdirectory, filename)

            # Export to PDF optional parameters
            data_frame = "PAGE_LAYOUT"
            df_export_width = 640
            df_export_height = 480
            resolution = 300
            image_quality = "BEST"
            colorspace = "RGB"
            compress_vectors = True
            image_compression = "ADAPTIVE"
            picture_symbol = "RASTERIZE_BITMAP"
            convert_markers = False
            embed_fonts = True
            layers_attributes = "LAYERS_ONLY"
            georef_info = True
            jpeg_compression_quality = 80

            # Run the export tool
            arcpy.mapping.ExportToPDF(mxd, outfile, data_frame,
                                      df_export_width, df_export_height,
                                      resolution, image_quality, colorspace,
                                      compress_vectors, image_compression,
                                      picture_symbol, convert_markers,
                                      embed_fonts, layers_attributes,
                                      georef_info, jpeg_compression_quality)
            arcpy.AddMessage("PDF is located: " + outfile)
            arcpy.AddMessage(filename)
            return filename

        elif export == 'JPEG':
            filename = filename_prefixe + map_doc_name + ".jpg"
            outfile = os.path.join(outputdirectory, filename)

            # Export to JEPG optional parameters
            data_frame = "PAGE_LAYOUT"
            df_export_width = 640
            df_export_height = 480
            resolution = 96
            world_file = False
            color_mode = "24-BIT_TRUE_COLOR"
            jpeg_quality = 100
            progressive = False

            # Run the export tool
            arcpy.mapping.ExportToJPEG(mxd, outfile, data_frame,
                                       df_export_width, df_export_height,
                                       resolution, world_file, color_mode,
                                       jpeg_quality, progressive)

            arcpy.AddMessage("JPEG is located: " + outfile)
            return filename

        elif export == 'TIFF':
            filename = filename_prefixe + map_doc_name + ".tif"
            outfile = os.path.join(outputdirectory, filename)

            # Export to JPEG optional parameters
            data_frame = "PAGE_LAYOUT"
            df_export_width = 640
            df_export_height = 480
            resolution = 96
            world_file = False
            color_mode = "24-BIT_TRUE_COLOR"
            tiff_compression = "LZW"

            # Run the export tool
            arcpy.mapping.ExportToTIFF(mxd, outfile, data_frame,
                                       df_export_width, df_export_height,
                                       resolution, world_file, color_mode,
                                       tiff_compression)
            arcpy.AddMessage("TIFF is located: " + outfile)
            return filename

        elif export == "MAP PACKAGE":
            filename = filename_prefixe + map_doc_name + ".mpk"
            outfile = os.path.join(outputdirectory, filename)
            dfextent = data_frame.extent
            mxd = mxd.filePath
            arcpy.AddMessage(mxd)

            # Export to MPK optional parameters
            convert_data = "CONVERT"
            convert_arcsde_data = "CONVERT_ARCSDE"
            apply_extent_to_arcsde = "ALL"
            arcgisruntime = "DESKTOP"
            reference_all_data = "NOT_REFERENCED"
            version = "ALL"

            # Run the export tool
            arcpy.PackageMap_management(mxd, outfile, convert_data,
                                        convert_arcsde_data, dfextent,
                                        apply_extent_to_arcsde, arcgisruntime,
                                        reference_all_data, version)
            arcpy.AddMessage("MPK is located: " + outfile)
            return filename

        elif export == 'LAYOUT GEOTIFF':
            filename = filename_prefixe + map_doc_name + ".tif"
            outfile = os.path.join(outputdirectory, filename)

            # Export to Layout GeoTIFF optional parameters:
            resolution = 96
            world_file = False
            color_mode = "24-BIT_TRUE_COLOR"
            tiff_compression = "LZW"

            # Run the export tool
            arcpyproduction.mapping.ExportToLayoutGeoTIFF(
                mxd, outfile, data_frame, resolution, world_file, color_mode,
                tiff_compression)
            arcpy.AddMessage("Layout GeoTIFF is located: " + outfile)
            return filename

        elif export == 'PRODUCTION PDF' or export == 'MULTI-PAGE PDF':
            filename = filename_prefixe + map_doc_name + ".pdf"
            outfile = os.path.join(outputdirectory, filename)
            setting_file = os.path.join(product_location, production_xml)

            if os.path.exists(setting_file) == True:
                arcpyproduction.mapping.ExportToProductionPDF(
                    mxd, outfile, setting_file)
                arcpy.AddMessage("Production PDF is located: " + outfile)
            else:
                arcpy.AddMessage(
                    "Production PDF is the default exporter for a Multi-page PDF."
                )
                arcpy.AddWarning(
                    "Color mapping rules file doesn't exist, using "
                    "standard ExportToPDF exporter with default "
                    "settings.")
                arcpy.mapping.ExportToPDF(mxd, outfile)
                arcpy.AddMessage("PDF is located: " + outfile)
            return filename

        else:
            arcpy.AddError("The exporter : " + export + " is not supported, "
                           "please contact your system administrator.")

    except arcpy.ExecuteError:
        arcpy.AddError(arcpy.GetMessages(2))
    except Exception as ex:
        arcpy.AddError(ex.message)
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]
        arcpy.AddError("Traceback info:\n" + tbinfo)
def execute(request):
    """Package inputs to an Esri map or layer package.
    :param request: json as a dict.
    """
    errors = 0
    skipped = 0
    layers = []
    files = []

    app_folder = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    parameters = request['params']
    out_format = task_utils.get_parameter_value(parameters, 'output_format',
                                                'value')
    summary = task_utils.get_parameter_value(parameters, 'summary')
    tags = task_utils.get_parameter_value(parameters, 'tags')
    output_file_name = task_utils.get_parameter_value(parameters,
                                                      'output_file_name')
    if not output_file_name:
        output_file_name = 'package_results'

    # Get the clip region as an extent object.
    clip_area = None
    try:
        clip_area_wkt = task_utils.get_parameter_value(parameters,
                                                       'processing_extent',
                                                       'wkt')
        clip_area = task_utils.get_clip_region(clip_area_wkt)
    except (KeyError, ValueError):
        pass

    out_workspace = os.path.join(request['folder'], 'temp')
    if not os.path.exists(out_workspace):
        os.makedirs(out_workspace)

    num_results, response_index = task_utils.get_result_count(parameters)
    # if num_results > task_utils.CHUNK_SIZE:
    # Query the index for results in groups of 25.
    query_index = task_utils.QueryIndex(parameters[response_index])
    fl = query_index.fl
    query = '{0}{1}{2}'.format(sys.argv[2].split('=')[1], '/select?&wt=json',
                               fl)
    fq = query_index.get_fq()
    if fq:
        groups = task_utils.grouper(range(0, num_results),
                                    task_utils.CHUNK_SIZE, '')
        query += fq
    elif 'ids' in parameters[response_index]:
        groups = task_utils.grouper(list(parameters[response_index]['ids']),
                                    task_utils.CHUNK_SIZE, '')
    else:
        groups = task_utils.grouper(range(0, num_results),
                                    task_utils.CHUNK_SIZE, '')

    headers = {
        'x-access-token': task_utils.get_security_token(request['owner'])
    }
    status_writer.send_status(_('Starting to process...'))
    for group in groups:
        if fq:
            results = requests.get(
                query +
                "&rows={0}&start={1}".format(task_utils.CHUNK_SIZE, group[0]),
                verify=verify_ssl,
                headers=headers)
        elif 'ids' in parameters[response_index]:
            results = requests.get(query +
                                   '{0}&ids={1}'.format(fl, ','.join(group)),
                                   verify=verify_ssl,
                                   headers=headers)
        else:
            results = requests.get(
                query +
                "&rows={0}&start={1}".format(task_utils.CHUNK_SIZE, group[0]),
                verify=verify_ssl,
                headers=headers)

        input_items = task_utils.get_input_items(
            results.json()['response']['docs'])
        if not input_items:
            input_items = task_utils.get_input_items(
                parameters[response_index]['response']['docs'])
        layers, files, errors, skipped = get_items(input_items, out_workspace)
    # else:
    #     input_items = task_utils.get_input_items(parameters[response_index]['response']['docs'])
    #     layers, files, errors, skipped = get_items(input_items, out_workspace)

    if errors == num_results:
        status_writer.send_state(status.STAT_FAILED,
                                 _('No results to package'))
        return

    try:
        if out_format == 'MPK':
            shutil.copyfile(
                os.path.join(app_folder, 'supportfiles', 'MapTemplate.mxd'),
                os.path.join(out_workspace, 'output.mxd'))
            mxd = arcpy.mapping.MapDocument(
                os.path.join(out_workspace, 'output.mxd'))
            if mxd.description == '':
                mxd.description = os.path.basename(mxd.filePath)
            df = arcpy.mapping.ListDataFrames(mxd)[0]
            for layer in layers:
                arcpy.mapping.AddLayer(df, layer)
            mxd.save()
            status_writer.send_status(
                _('Generating {0}. Large input {1} will take longer to process.'
                  .format('MPK', 'results')))
            if arcpy.GetInstallInfo()['Version'] == '10.0':
                arcpy.PackageMap_management(
                    mxd.filePath,
                    os.path.join(os.path.dirname(out_workspace),
                                 '{0}.mpk'.format(output_file_name)),
                    'PRESERVE',
                    extent=clip_area)
            elif arcpy.GetInstallInfo()['Version'] == '10.1':
                arcpy.PackageMap_management(
                    mxd.filePath,
                    os.path.join(os.path.dirname(out_workspace),
                                 '{0}.mpk'.format(output_file_name)),
                    'PRESERVE',
                    extent=clip_area,
                    ArcGISRuntime='RUNTIME',
                    version='10',
                    additional_files=files,
                    summary=summary,
                    tags=tags)
            else:
                arcpy.PackageMap_management(
                    mxd.filePath,
                    os.path.join(os.path.dirname(out_workspace),
                                 '{0}.mpk'.format(output_file_name)),
                    'PRESERVE',
                    extent=clip_area,
                    arcgisruntime='RUNTIME',
                    version='10',
                    additional_files=files,
                    summary=summary,
                    tags=tags)
            #  Create a thumbnail size PNG of the mxd.
            task_utils.make_thumbnail(
                mxd, os.path.join(request['folder'], '_thumb.png'))
        else:
            status_writer.send_status(
                _('Generating {0}. Large input {1} will take longer to process.'
                  .format('LPK', 'results')))
            for layer in layers:
                if layer.description == '':
                    layer.description = layer.name
            if arcpy.GetInstallInfo()['Version'] == '10.0':
                arcpy.PackageLayer_management(
                    layers,
                    os.path.join(os.path.dirname(out_workspace),
                                 '{0}.lpk'.format(output_file_name)),
                    'PRESERVE',
                    extent=clip_area,
                    version='10')
            else:
                arcpy.PackageLayer_management(
                    layers,
                    os.path.join(os.path.dirname(out_workspace),
                                 '{0}.lpk'.format(output_file_name)),
                    'PRESERVE',
                    extent=clip_area,
                    version='10',
                    additional_files=files,
                    summary=summary,
                    tags=tags)
            #  Create a thumbnail size PNG of the mxd.
            task_utils.make_thumbnail(
                layers[0], os.path.join(request['folder'], '_thumb.png'))
    except (RuntimeError, ValueError, arcpy.ExecuteError) as ex:
        status_writer.send_state(status.STAT_FAILED, repr(ex))
        return

    # Update state if necessary.
    if errors > 0 or skipped:
        status_writer.send_state(
            status.STAT_WARNING,
            _('{0} results could not be processed').format(errors + skipped))
    task_utils.report(os.path.join(request['folder'], '__report.json'),
                      num_results - (skipped + errors), skipped, errors,
                      errors_reasons, skipped_reasons)
Example #8
0
                    addCommentsToFc(existingFc, "esriGeometryPolyline",
                                    "redline-graphicslayer", "remarks")
                elif layer.name == "polygonLayer":
                    addCommentsToFc(existingFc, "esriGeometryPolygon",
                                    "redline-graphicslayer", "remarks")

        # package map doc
        # tool requires doc to have a description
        generatedMapDoc = mapping.MapDocument(generatedMxdFilePath)
        generatedMapDoc.description = "Auckland Council web viewer export graphics map document"
        generatedMapDoc.save()

        log("Packaging map: " + generatedMxdFilePath)
        log("Saving to: " + outMpk)
        arcpy.PackageMap_management(generatedMxdFilePath, outMpk, "CONVERT",
                                    "CONVERT_ARCSDE", "#", "ALL", "DESKTOP",
                                    "NOT_REFERENCED", "10.1",
                                    [outWebmapTextFilePath])

        # supply location to client
        resultObj["url"] = outMpkUrl

    # shapefiles need generating from gp service
    if inputFileId:

        # unzip uploaded files
        uploadPathRoot = path.join(serverUploadPath, inputFileId)

        if not path.isdir(uploadPathRoot):
            raise Exception("Upload directory not found: " + uploadPathRoot)

        # find a map package in uploads
Example #9
0
import arcpy, os, sys

mxd_path = r'D:\BCASProjects\CREL\Co-Management\CWS\CWS_a4.mxd'

Map_title = "Chunati WS Total Forest Loss (2001-2012)"

mpk_path = r'D:\Database\CREL_Database\CREL_DATABASE\Satchari_National_Park\MPKs'

full_mpk_path = os.path.join(mpk_path, Map_title + '_Hansen_Analysis')
mxd = arcpy.mapping.MapDocument('CURRENT')
mxd.title = Map_title
mxd.summary = "These data is generated from Rapid Eye (2013-2014) and Landsat images are used"
mxd.description = "This map is produced after an analysis of Hansen data and RapidEye images to track the land cover change over 12 years (2001-20012) in the CREL sites."
mxd.author = "CREL"
mxd.credits = "CREL,BCAS"
mxd.tags = "Hansen,Landcover Change"
mxd.hyperlinkBase = mxd_path.split("'")[0]
mxd.relativePaths = 'True'
arcpy.RefreshTOC()

arcpy.PackageMap_management(mxd_path, full_mpk_path + '.mpk', "CONVERT",
                            "PRESERVE_ARCSDE", "DISPLAY", "ALL", "DESKTOP",
                            "NOT_REFERENCED", "ALL")
Example #10
0
arcpy.AddMessage('Writing report to ' + reportPath)

# start writing report text to a string variable
reportText = 'Title: ' + mxd.title + '\n'
reportText += 'Author: ' + mxd.author + '\n'
reportText += 'Description: ' + mxd.description + '\n'
reportText += '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' + '\n'

# if the user chose to do so, create map package
if packageMap:
    packagePath = outDir + '\\' + mxd.title.replace('.', '_') + '.mpk'
    if (os.path.exists(packagePath)):
        arcpy.AddMessage('Map package already exists (' + packagePath + ')')
    else:
        arcpy.AddMessage('Creating map package (' + packagePath + ')')
        arcpy.PackageMap_management(mxd.filePath, packagePath)

# loop thru all data frames in the map
dataFrames = mapping.ListDataFrames(mxd, '')
for frame in dataFrames:
    # report data frame name and spatial reference
    reportText += '\nData Frame: ' + frame.name + '\n'
    reportText += 'Spatial Reference: ' + frame.spatialReference.name + '\n'
    # get all layers in this data frame
    layers = mapping.ListLayers(mxd, '', frame)
    i = 0  # layer index position
    # loop thru all layers in the data frame
    for lyr in layers:
        # report index position and name
        reportText += '\tLayer ' + str(i) + ': ' + lyr.name + '\n'
        i += 1  # same as i = i + 1