Skip To Content

ConvertWebMapToArcGISProject

Summary

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

Discussion

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

The ConvertWebMapToArcGISProject function is primarily intended for workflows where the web map needs to be modified or exported using arcpy.mp functions. Some example workflows that can be met using the ConvertWebMapToArcGISProject function are as follows:

  • Swapping out service layers for local vector data—In arcpy.mp scripts, service layers can be identified and swapped out for layers that point to local data. This is commonly used when a vector output is preferred rather than service layers. For example, vector PDF output supports the following in PDF viewing applications: toggling layer visibility, viewing feature attributes, and viewing map coordinates. One way to accomplish swapping service layers for vector data is to stage layout templates that contain vector equivalents of all the possible service layers. After executing the ConvertWebMapToArcGISProject function, loop through all the layers in the output map, and remove all layers except the vector layers that correspond to the service layers in the web map. This workflow would be used when swapping your own services with the corresponding vector data that you already have.
  • Creating map books—A map book can be generated if Map Series is enabled on the template_pagx. Moreover, the output layout can be exported as a PDF file and inserted into other PDF files using the PDFDocument class to create a complete map book.
  • Exporting using advanced options—All of the arcpy.mp export functions have many advanced options. For example, the ExportToPDF functions available on the Layout and MapView classes have parameters for controlling raster and vector compression, defining colorspace, embedding fonts, and so on.
Note:

ArcGIS Server also includes a geoprocessing service named PrintingTools. The PrintingTools service can be used in a web app to generate a high-cartographic-quality printable image. For more information regarding the PrintingTools service, see the following:

The output of the Python script can be a layout from the optional template_pagx parameter and can include page layout surrounds (for example, title, legends, scale bar, overview map frames, and so on). The output can also be a MapView, which would not include any page layout surrounds.

Once you have a Python script that prepares the map for printing, you can encapsulate it in a geoprocessing script tool. You can then publish the script tool as an ArcGIS Server web tool. The ArcGIS API for JavaScript and Web AppBuilder for ArcGIS have a Print Task and a Print Widget that you can use in your web GIS app. Both the Print Task and the Print Widget have a URL property that points to the REST URL of the web tool you created.

When using ConvertWebMapToArcGISProject in a web tool in the ArcGIS API for JavaScript or Web AppBuilder for ArcGIS, the parameter names of the script tool must match the Print Task or Print Widget parameters:

Parameter NameData TypeExplanation
Web_Map_as_JSON

String

A JSON representation of the state of the map to be exported as it appears in the web app. The ArcGIS API for JavaScript and Web AppBuilder for ArcGIS allow you to easily get this JSON string from the web app.

Output_File

File

The output file name. The extension of the file depends on the Format parameter.

Format

String

The format in which the map image for printing will be delivered. The following strings are accepted:

  • PNG8 (default if the parameter is left blank)
  • PNG
  • PDF
  • PNG32
  • JPG
  • GIF
  • EPS
  • SVG
  • SVGZ

Layout_Template

String

Either a name of a template from the list or the keyword MAP_ONLY. When MAP_ONLY is chosen or an empty string is passed in, the output map does not contain any page layout surroundings (for example, title, legends, and scale bar).

Only Web_Map_as_JSON and Output_File are required.

Tip:

Any number of additional user-defined parameters can also be added. The ability to pass extra parameters into a custom print task is useful, as it allows you to collect any number of extra parameters from the web app and pass them into the Python script.

ConvertWebMapToArcGISProject is most commonly used when printing a map from a web app. When you use the ArcGIS API for JavaScript or Web AppBuilder for ArcGIS Print Task or Print Widget, you don't need to create the web map JSON; the APIs take care of it for you. However, before the script can be published and used in the web APIs, it must be run locally. Any valid web map JSON string can be used when running the script locally. A JSON string similar to what your web app will be returning may be required for your script to run successfully. See ExportWebMap specification to understand how this text should be formatted. A sample string is below:

{
    "layoutOptions": {
        "titleText": "Simple WebMap JSON example"
    },
    "operationalLayers": [
        {
            "url": "http://maps1.arcgisonline.com/ArcGIS/rest/services/USA_Federal_Lands/MapServer",
            "visibility": true
        }
    ],
    "exportOptions": {
        "outputSize": [
            1500,
            1500
        ]
    },
    "mapOptions": {
        "extent": {
            "xmin": -13077000,
            "ymin": 4031000,
            "xmax": -13023000,
            "ymax": 4053000
        }
    },
    "version": "1.4"
}

When running the script tool, the JSON string can be copied and pasted into the Web_Map_as_JSON input parameter. However, the line breaks must be removed for the string to be valid input. A sample JSON string with line breaks removed is below:

{"layoutOptions": {"titleText": "Simple WebMap JSON example"},"operationalLayers": [{"url": "http://maps1.arcgisonline.com/ArcGIS/rest/services/USA_Federal_Lands/MapServer","visibility": true}],"exportOptions": {"outputSize": [1500,1500]},"mapOptions": {"extent": {"xmin": -13077000,"ymin": 4031000,"xmax": -13023000,"ymax": 4053000}},"version": "1.4"}

Tip:

For publishing purposes, you can leave the Web_Map_as_JSON input parameter blank, as the ArcGIS Web APIs will provide the web map JSON in the web app. You can leave the Web_Map_as_JSON input parameter blank provided the Python script was written in such a way as to not fail with blank input. For example, the script doesn't look for web map layers by name. It is good practice to ensure the script works locally before publishing by testing with a valid web map JSON string.

Tip:

As mentioned previously, the JSON string returned from the ArcGIS Web APIs contains the full state of the web map. The layoutOptions object in the JSON string warrants extra discussion, as it will automatically update layout elements that can be staged in the template_pagx. For example, if the JSON has a titleText setting, and the template_pagx has a title dynamic text element, the title in the template page layout will be updated with the titleText value. For more information, see the layoutOptions section in the ExportWebMap specification.

When you encapsulate the Python script that uses ConvertWebMapToArcGISProject in a web tool, you need to ensure that ArcGIS Server can access the layout templates and data used in the web app. It is best practice to use a folder that is registered with ArcGIS Server. For more information on registering data, see the following:

In addition to creating your own layout templates, you can also use the templates that ship with the software. They are located at <installation_directory>\Templates\ExportWebMapTemplates. These templates contain map elements such as a legend, current date dynamic text, a scale bar, and scale text. These templates are a good starting off point. However, keep in mind that they are part of the installation directory and will be removed if the software is ever uninstalled or reinstalled. These templates can be manually copied to a location that ArcGIS Server can access.

By default, notes overlays or client-side graphics from the web app will be stored in an in-memory workspace. The in-memory workspace is temporary and is deleted when the app is closed. To make a permanent copy of the output project that contains notes overlays, specify a notes_gdb; then use the saveACopy method from the ArcGISProject class.

If your web app uses dynamic layers, the updateLayerFromJSON function from the Layer class can be used to update the properties (for example, symbology) of staged vector layers in the layout template with the layer definition of dynamic layers 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.

Syntax

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

The web map for printing in JavaScript Object Notation (JSON). See the ExportWebMap JSON specification for more information. The ArcGIS API for JavaScript and the Web AppBuilder for ArcGIS allow developers to easily 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 webmap map frame (and all other map frames) will be preserved in the output ArcGISProject. If no template_pagx is specified, use the Map'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).

(The default value is 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.

(The default value is 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.

(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. 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.

Code sample

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) is used that contains vector equivalents of all the possible service layers. 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 = 'C:/Austin/Templates'

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

# Format for output
Format = arcpy.GetParameterAsText(1)
if Format == '#' or not Format:
    Format = "PDF" 

# Input Layout template
Layout_Template = arcpy.GetParameterAsText(2)
if Layout_Template == '#' or not Layout_Template:
    Layout_Template = "Austin26x28" 
    
# Extra parameter - georef_info
Georef_info = arcpy.GetParameterAsText(3)
if Georef_info == '#' or not Georef_info:
    Georef_info = "False"

# 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 + 'WebMercator.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
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 map document
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 a map document
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