ConvertWebMapToArcGISProject

Summary

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

Discussion

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 Experience Builder, ArcGIS API for JavaScript or ArcGIS Web AppBuilder.

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

Syntax

ConvertWebMapToArcGISProject (webmap_json, {template_pagx}, {mapframe_name}, {notes_gdb}, {report_template})
ParameterExplanationData Type
webmap_json

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

String
template_pagx

The path and file name to a layout file (.pagx) that will be used 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 below. Layers in the template_pagx file's web map map frame (and all other map frames) will be preserved in the output ArcGISProject object. If no template_pagx value is provided, use the defaultView property on the Map class to access the web map's MapView object. 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).

Alternatively, you can use the portal ID (in JSON format) of the layout item in the currently active portal that will be used for templates. Use the format {"id": "<portal-id>"}. You can use SignInToPortal to sign in to a portal that contains layout items.

(The default value is None)

String
mapframe_name

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 value can be provided. The function returns an error if there are multiple map frames but no map frame named WEBMAP_MAP_FRAME is found and no mapframe_name value has been provided.

(The default value is None)

String
notes_gdb

The path to a new or existing file geodatabase or an existing enterprise geodatabase connection where graphic features will be written. Use this parameter only when 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.

(The default value is None)

String
report_template

The path and file name to a report template file (.rptt) or report definition file (.rptx) that will be used as the optional template for a report. If the webmap_json contains reportOptions, a Report object will be present in the ArcGISProject return object that can then be exported. The report can be accessed using the listReports function on the ArcGISProject class.

Alternatively, you can use the portal ID (in JSON format) of the report item in the currently active portal that will be used for templates. Use the format {"id": "<portal-id>"}. You can use SignInToPortal to sign in to a portal that contains report items.

(The default value is None)

String
Return Value
Data TypeExplanation
tuple

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

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

Code sample

ConvertWebMapToArcGISProject example 1

In this example, the script reads in a web map JSON. The output MapView object from ConvertWebMapToArcGISProject is exported to a .png file. The output map does not contain any page layout surroundings (for example, title, legends, or 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, or 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, 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 4

In this example, the script reads in a web map JSON, a layout template, and existing PDFs to which the web map will be appended. The output layout from the ConvertWebMapToArcGISProject function is exported as a PDF and inserted into other PDFs 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 5

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.management.SelectLayerByLocation(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 6

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 AllSource 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 PDFs 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 7

This example demonstrates how to access the selected features from a feature service in the web map and display them in a table frame. The table frame in the staged layout template (.pagx file) uses a temporary layer that is removed in the script. This sample uses Python CIM access to update the source of the table frame to a layer from the web map.

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"

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

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

# Reference variables in the ArcGIS Project
layout = aprx.listLayouts()[0]
m = aprx.listMaps('Web Map')[0]

# Remove the layer in the layout template that was used to create the table
m.removeLayer(m.listLayers("TempLayerForTable")[0])

# Reference a layer from the web map json that contains the selected features
lyr = m.listLayers()[0]

# Get the fields from the web map layer
lyr_fields = arcpy.ListFields(lyr)

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

# Get the CIM definition for the layout
layCIM = layout.getDefinition("V3")   

# Get the table frame from the CIM
for elm in layCIM.elements:
    if elm.name == 'Table Frame':
        # Point the table frame to the layer from the Web Map
        elm.mapMemberURI = lyr.URI
        
        # Apply the selection set to the Table Frame, otherwise show all records
        if oids is not None:
            sql = 'OBJECTID IN {}'.format(str(oids)).replace('{', '(').replace('}', ')')       
            elm.customWhereClause = sql
            
        # Use the fields from the web map layer in the table frame
        for x in range(len(elm.fields) - 1):
            elm.fields[x].name = lyr_fields[x + 1].name
            
        # Set Layout CIM definition
        layout.setDefinition(layCIM) 

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

# Set the output parameter to be the output PDF
arcpy.SetParameterAsText(2, LayoutPDF)
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