ConvertWebMapToArcGISProject

概要

Converts a web map (in JavaScript Object Notation [JSON] format) that you intend to print or export to an ArcGISProject. The ArcGIS project can be further modified before being printed or exported.

ディスカッション

The ConvertWebMapToArcGISProject function converts a web map that you intend to print or export to an ArcGIS Pro project. Once the web map is converted, the full state of the web map exists in the project. The project can then be further modified before being printed or exported to a common format such as PDF. ConvertWebMapToArcGISProject is most commonly used when printing a map from a web GIS app using ArcGIS API for JavaScript or ArcGIS Web AppBuilder.

For a more detailed discussion, scenarios, and code samples, see Web Map Printing with arcpy.mp.

構文

ConvertWebMapToArcGISProject (webmap_json, {template_pagx}, {mapframe_name}, {notes_gdb})
パラメーター説明データ タイプ
webmap_json

The web map for printing in JSON. See the ExportWebMap JSON specification for more information. ArcGIS API for JavaScript and ArcGIS Web AppBuilder allow developers to get this JSON string from the web app.

String
template_pagx

A string representing the path and file name to a layout file (.pagx) to use as the optional template for the page layout. The web map is converted to a new map in the ArcGIS project. A 2D map frame on the layout will reference the newly created map. For more information, see the mapframe_name parameter. Layers in the template_pagx file's web map map frame (and all other map frames) will be preserved in the output ArcGISProject. If no template_pagx is specified, use the Map object's defaultView function to access the web map's MapView. In the MapView web map printing workflow, the output file will not contain any layout surrounds (for example, title, legends, scale bar, overview map frames, and so on).

(デフォルト値は次のとおりです None)

String
mapframe_name

A string representing the name of a map frame on the layout whose source will be updated to point to the newly created map containing the web map JSON. If there is only one map frame on the layout, it will be used to reference the web map by default. If there is more than one map frame on the layout, and if this parameter is omitted, the map frame named WEBMAP_MAP_FRAME is used. Alternatively, a user-defined mapframe_name can be specified. The function throws an error if there are multiple map frames but no map frame named WEBMAP_MAP_FRAME is found and no mapframe_name has been specified.

(デフォルト値は次のとおりです None)

String
notes_gdb

A string representing the path to a new or existing file geodatabase or an existing enterprise geodatabase connection where graphic features should be written. This parameter should only be used if graphic features from the web map JSON need to be preserved permanently. In most cases, this parameter is not required as a temporary in-memory workspace will be used to store graphic features. This parameter allows you to save graphic features to persistent storage. The path must end with a .gdb or an .sde extension.

(デフォルト値は次のとおりです None)

String
戻り値
データ タイプ説明
tuple

Returns a Python-named tuple of web map and request properties.

  • ArcGISProjectThe ArcGISProject object created as output of the function. The ArcGISProject is created in memory. To make a permanent copy of the project on disk, call the saveACopy function on the ArcGISProject.
  • DPIThe requested DPI of the export from the web app.
  • outputSizeHeightThe height of the image as specified from the web app. Can be used when performing a map view export.
  • outputSizeWidthThe width of the image as specified from the web app. Can be used when performing a map view export.

コードのサンプル

ConvertWebMapToArcGISProject example 1

In this example, the script reads in a web map JSON. The output MapView from ConvertWebMapToArcGISProject is exported to a PNG file. The output map does not contain any page layout surroundings (for example, title, legends, and scale bar).

import arcpy
import os
import uuid

# Input web map json
Web_Map_as_JSON = arcpy.GetParameterAsText(0)

# Convert the web map to an ArcGIS Project
result = arcpy.mp.ConvertWebMapToArcGISProject(Web_Map_as_JSON)
aprx = result.ArcGISProject

# Get the map view
m = aprx.listMaps()[0]
mv = m.defaultView

# Use the uuid module to generate a GUID as part of the output name
# This will ensure a unique output name
output = 'WebMap_{}.png'.format(str(uuid.uuid1()))
Output_File = os.path.join(arcpy.env.scratchFolder, output)

# Export the web map
mv.exportToPNG(Output_File, result.outputSizeWidth, result.outputSizeHeight, result.DPI)

# Set the output parameter to be the output file of the server job
arcpy.SetParameterAsText(1, Output_File)

# Clean up
del mv, m, aprx, result
ConvertWebMapToArcGISProject example 2

In this example, the script reads in a web map JSON. The output MapView extent from ConvertWebMapToArcGISProject is modified before it is exported to a PNG file. The exportToPNG function uses user-defined values for the height, width, world_file, and color_mode parameters. The output map does not contain any page layout surroundings (for example, title, legends, and scale bar).

import arcpy
import os
import uuid

# Input web map json
Web_Map_as_JSON = arcpy.GetParameterAsText(0)

# Convert the web map to an ArcGIS Project
result = arcpy.mp.ConvertWebMapToArcGISProject(Web_Map_as_JSON)
aprx = result.ArcGISProject

# Get the map view
m = aprx.listMaps()[0]
mv = m.defaultView

# Change the extent of the map view
ext = mv.camera.getExtent()
ext.XMin = ext.XMin + 100
ext.YMin = ext.YMin + 100
ext.XMax = ext.XMax + 100
ext.YMax = ext.YMax + 100
mv.camera.setExtent(ext)

# Use the uuid module to generate a GUID as part of the output name
# This will ensure a unique output name
output = 'WebMap_{}.png'.format(str(uuid.uuid1()))
Output_File = os.path.join(arcpy.env.scratchFolder, output)

# Export the web map
mv.exportToPNG(Output_File, width=1000, height=1000, world_file=True, color_mode="32-BIT_WITH_ALPHA")

# Set the output parameter to be the output file of the server job
arcpy.SetParameterAsText(1, Output_File)

# Clean up
del mv, m, aprx, result
ConvertWebMapToArcGISProject example 3

In this example, a staged layout template (.pagx file) that contains vector equivalents of all the possible service layers is used. After executing the ConvertWebMapToArcGISProject function, the script loops through all the layers in the output map, removing all the service layers from the web map JSON, leaving just the staged vector layers. The output layout is then exported to either a PDF or PNG file. This example also shows how to pass extra parameters (Georef_info) from the web app to the Python script beyond the standard parameters supported by the Print Task.

import arcpy
import os
import uuid

# The template location in the server data store
templatePath = '//MyServer/MyDataStore/Templates'

# Input WebMap JSON
Web_Map_as_JSON = arcpy.GetParameterAsText(0)

# Format for output
Format = arcpy.GetParameterAsText(1)

# Input layout template
Layout_Template = arcpy.GetParameterAsText(2)
    
# Extra parameter - georef_info
Georef_info = arcpy.GetParameterAsText(3)

# Convert Georef_info string to boolean
if Georef_info.lower() == 'false': 
    Georef_info_bol = False
elif Georef_info.lower() == 'true': 
    Georef_info_bol = True
else:
    Georef_info_bol = True

# Get the requested layout template pagx file
templatePagx = os.path.join(templatePath, Layout_Template + '.pagx')
   
# Convert the WebMap to an ArcGISProject
result = arcpy.mp.ConvertWebMapToArcGISProject(Web_Map_as_JSON, templatePagx, "Layers Map Frame")
aprx = result.ArcGISProject
layout = aprx.listLayouts()[0]

# Reference the map that contains the webmap
m = aprx.listMaps('Web Map')[0]

# Remove the service layer
# This will just leave the vector layers from the template
for lyr in m.listLayers():
    if lyr.isWebLayer:
        m.removeLayer(lyr)
        
# Use the uuid module to generate a GUID as part of the output name
# This will ensure a unique output name
output = 'WebMap_{}.{}'.format(str(uuid.uuid1()), Format)
Output_File = os.path.join(arcpy.env.scratchFolder, output)

# Export the WebMap - use Georef_info_bol to control georeferencing
if Format.lower() == 'pdf':
    layout.exportToPDF(Output_File, georef_info=Georef_info_bol) 
elif Format.lower() == 'png':
    layout.exportToPNG(Output_File, world_file=Georef_info_bol)

# Set the output parameter to be the output file of the server job
arcpy.SetParameterAsText(4, Output_File) 

# Clean up
del layout, aprx, result
ConvertWebMapToArcGISProject example 4

In this example, the updateLayerFromJSON function from the Layer class is used to update the properties (for example, symbology) of a staged vector layer in the layout template with the layer definition of a dynamic layer from the web map JSON. This is useful if your web app allows changing the symbology of dynamic layers, and you want to replace the service layers with staged vector data but still maintain the updated symbology from the web app.

import arcpy
import os
import uuid
import json

# The template location in the server data store
templatePath = '//MyMachine/MyDataStore/WebMap'

# Input WebMap json
Web_Map_as_JSON = arcpy.GetParameterAsText(0)

# Input Layout template
Layout_Template = arcpy.GetParameterAsText(1)
if Layout_Template == '#' or not Layout_Template:
    Layout_Template = "Landscape11x17" 

# Get the requested layout template
templatePagx = os.path.join(templatePath, Layout_Template + '.pagx')

# Convert the web map to an ArcGIS Project
result = arcpy.mp.ConvertWebMapToArcGISProject(webmap_json, templatePagx)
aprx = result.ArcGISProject

# Reference the map that contains the web map
m = aprx.listMaps('Web Map')[0]

# Reference the staged vector data that corresponds to the dynamic layer in the JSON
# This is the layer that will get updated based on the layer definition in the JSON
lyr = m.listLayers("U.S. States (Generalized)")[0]

# Read the JSON and extract the layer definition
# In this case we have hardcoded it to second operational layer
data = json.loads(Web_Map_as_JSON)
layerDefinition = data["operationalLayers"][1]

# Update the staged vector layer with the layer definition (e.g. renderer info) from the JSON
lyr.updateLayerFromJSON(layerDefinition)

# Remove all service layers. This will leave only staged vector layers.
for slyr in m.listLayers():
    if slyr.isServiceLayer:
        m.removeLayer(slyr)

# Use the uuid module to generate a GUID as part of the output name
# This will ensure a unique output name
output = 'WebMap_{}.pdf'.format(str(uuid.uuid1()))
Output_File = os.path.join(arcpy.env.scratchFolder, output)

# Export the web map
layout = aprx.listLayouts()[0]
layout.exportToPDF(Output_File)

# Set the output parameter to be the output file of the server job
arcpy.SetParameterAsText(2, Output_File)

# Clean up
del layout, m, aprx, result
ConvertWebMapToArcGISProject example 5

In this example, the script reads in a web map JSON, a layout template, and existing PDF documents to which the web map will be appended. The output layout from the ConvertWebMapToArcGISProject function is exported as a PDF file and inserted into other PDF files using the PDFDocument class.

import arcpy
import os
import uuid

# The template location in the server data store
templatePath = '//MyMachine/MyDataStore/MapBook'

# Input WebMap json
Web_Map_as_JSON = arcpy.GetParameterAsText(0)

# Input Layout template
Layout_Template = arcpy.GetParameterAsText(1)
if Layout_Template == '#' or not Layout_Template:
    Layout_Template = "LandscapeLetter" 

# PDF Title Page
PDF_Title = arcpy.GetParameterAsText(2)
if PDF_Title == '#' or not PDF_Title:
    PDF_Title = "TitlePage.pdf"

# PDF End Page
PDF_End = arcpy.GetParameterAsText(3)
if PDF_End == '#' or not PDF_End:
    PDF_End = "ContactInfo.pdf"

# Get the requested layout template
templatePagx = os.path.join(templatePath, Layout_Template + '.pagx')

# Get the requested PDF files
PDF_Title_File = os.path.join(templatePath, PDF_Title)
PDF_End_File = os.path.join(templatePath, PDF_End)

# Convert the WebMap to an ArcGIS Project
result = arcpy.mp.ConvertWebMapToArcGISProject(Web_Map_as_JSON, 
                                               templatePagx)
aprx = result.ArcGISProject
layout = aprx.listLayouts()[0]

# Use the uuid module to generate a GUID as part of the output name
# This will ensure a unique output name
WebMapPDF = os.path.join(arcpy.env.scratchFolder, 
                         'WebMap_{}.pdf'.format(str(uuid.uuid1())))

# Export the WebMap to PDF
layout.exportToPDF(WebMapPDF)

# Create a new "master" output PDF Document
# Append Title, WebMap and End PDFs to it
Output_Name = os.path.join(arcpy.env.scratchFolder, 
                           'OutputWithWebMap_{}.pdf'.format(str(uuid.uuid1())))
pdfDoc = arcpy.mp.PDFDocumentCreate(Output_Name)
pdfDoc.appendPages(PDF_Title_File)
pdfDoc.appendPages(WebMapPDF)
pdfDoc.appendPages(PDF_End_File)
pdfDoc.saveAndClose()

# Set the output parameter to be the output PDF
arcpy.SetParameterAsText(4, Output_Name)

# Clean up
del aprx, result, layout
ConvertWebMapToArcGISProject example 6

In this example, a staged layout template (.pagx file) that has a Spatial Map Series enabled is used. The map series index features that intersect the extent of the web map are exported to a multipage PDF.

import sys, os, arcpy, uuid

# The template location in the server data store
templatePath = '//MyServer/MyDatastore/Templates'

# Input web map json
Web_Map_as_JSON = arcpy.GetParameterAsText(0)

# Format for output (PDF)
Format = arcpy.GetParameterAsText(1)

# Define output PDF file name
pdfMapSeries = os.path.join(arcpy.env.scratchFolder, 'WebMapSeries_{}.pdf'.format(str(uuid.uuid1())))

# Input Layout template
Layout_Template = arcpy.GetParameterAsText(2)
templatePagx = os.path.join(templatePath, Layout_Template)

# Convert the web map to an ArcGIS Project
result = arcpy.mp.ConvertWebMapToArcGISProject(Web_Map_as_JSON, templatePagx, 'Series Map Frame')
aprx = result.ArcGISProject
layout = aprx.listLayouts('Layout')[0]
ms = layout.mapSeries
mf = layout.listElements('MAPFRAME_ELEMENT', 'Series Map Frame')[0]

# Get the extent of the mapframe from the web map as a geometry object
extent = mf.camera.getExtent().polygon

# This the Map Series index layer
mapSeriesLyr = mf.map.listLayers("World Countries")[0]

# Select the map series index features that intersect the web map extent
arcpy.SelectLayerByLocation_management(mapSeriesLyr, "INTERSECT", extent, selection_type="NEW_SELECTION")

# Display a message indicating which page numbers will be exported
pageRange = ', '.join(str(e) for e in ms.selectedIndexFeatures)
arcpy.AddMessage('Exporting the following map series page numbers: ' + pageRange)

# Export the selected Map Series pages
ms.exportToPDF(pdfMapSeries, 'SELECTED')

# Set the output parameter to be the output file of the server job
arcpy.SetParameterAsText(3, pdfMapSeries)
ConvertWebMapToArcGISProject example 7

This example demonstrates how to access the selected features from a feature service in the web map and display them in a report. The importDocument function on the ArcGISProject class is used to import a report file (.rptx) into the ArcGIS Pro project that is returned from ConvertWebMapToArcGISProject. By default, the report will only show selected features. The Report class is used to set the report's data source. The output layout and report are exported as PDF files and appended together using the PDFDocument class.

import arcpy
import os
import uuid

# The template location in the server data store
templatePath = '//MyServer/MyDataStore/Templates'

# Input WebMap json
Web_Map_as_JSON = arcpy.GetParameterAsText(0)

# Input layout template
Layout_Template = arcpy.GetParameterAsText(1)
if Layout_Template == '#' or not Layout_Template:
	Layout_Template = "Landscape_Letter_Layout"

# Input report template
Report_Template = arcpy.GetParameterAsText(2)
if Report_Template == '#' or not Report_Template:
	Report_Template = "Landscape_Letter_Report"

# Get the requested layout template
templatePagx = os.path.join(templatePath, Layout_Template + '.pagx')

# Get the requested report template
templateReport = os.path.join(templatePath, Report_Template + '.rptx')

# Convert the WebMap to an ArcGIS Project
result = arcpy.mp.ConvertWebMapToArcGISProject(Web_Map_as_JSON, 
                                               templatePagx, 
                                               "Map Frame")
aprx = result.ArcGISProject

# Import the report template
aprx.importDocument(templateReport)
report = aprx.listReports()[0]

# Reference the layer from the web map that the report will be based on 
lyr = aprx.listMaps('Web Map')[0].listLayers('Sample Sites')[0] 

# Change the report data source to be the layer from the web map
report.setReferenceDataSource(lyr)

# Get the selected feature ObjectIDs from the web map layer
oids = lyr.getSelectionSet()

# The report template is configured to only export selected features
if oids is not None:
        # Export the report to PDF
        ReportPDF = os.path.join(arcpy.env.scratchFolder, 
                                 'WebMapReport_{}.pdf'.format(str(uuid.uuid1())))
        report.exportToPDF(ReportPDF) 

        # Export the layout to PDF
        LayoutPDF = os.path.join(arcpy.env.scratchFolder, 
                                 'WebMapLayout_{}.pdf'.format(str(uuid.uuid1())))
        layout = aprx.listLayouts('Layout')[0]
        layout.exportToPDF(LayoutPDF)

        # Append the report to the layout PDF
        pdfDoc = arcpy.mp.PDFDocumentOpen(LayoutPDF)
        pdfDoc.appendPages(ReportPDF)
        pdfDoc.saveAndClose()

        # Set the output parameter to be the output PDF
        arcpy.SetParameterAsText(3, LayoutPDF)

# Clean up
del aprx, result, layout, report, lyr
ConvertWebMapToArcGISProject example 8

In this example, the ImportCredentials function is used to access ArcGIS Server secured services.

import arcpy
import os
import uuid

# The template location in the server data store
templatePath = '//MyServer/MyDataStore/Templates'

# Input WebMap JSON
Web_Map_as_JSON = arcpy.GetParameterAsText(0)

# Input layout template
Layout_Template = arcpy.GetParameterAsText(1)

# Get the requested layout template pagx file
templatePagx = os.path.join(templatePath, Layout_Template + '.pagx')

# Specify credentials for secured services in the WebMap JSON
secure_server_connections = [os.path.join(templatePath, 'secured.ags'), 
                             os.path.join(templatePath, 'secured.wms')]

# Import credentials
importedConnections = arcpy.ImportCredentials(secure_server_connections)
   
# Convert the WebMap to an ArcGISProject
result = arcpy.mp.ConvertWebMapToArcGISProject(Web_Map_as_JSON, templatePagx, "Layers Map Frame")
aprx = result.ArcGISProject
layout = aprx.listLayouts()[0]
        
# Use the uuid module to generate a GUID as part of the output name
# This will ensure a unique output name
output = 'WebMap_{}.pdf'.format(str(uuid.uuid1()))
Output_File = os.path.join(arcpy.env.scratchFolder, output)

# Export the WebMap 
layout.exportToPDF(Output_File) 

# Set the output parameter to be the output file of the server job
arcpy.SetParameterAsText(3, Output_File) 

# Clear credentials
arcpy.ClearCredentials(importedConnections)

# Clean up
del layout, aprx, result