ConvertWebMapToArcGISProject

摘要

将要打印或导出的 Web 地图(JSON 格式)转换为 ArcGISProject 对象。 可在打印或导出 ArcGIS 工程之前对其进行进一步修改。

说明

Web 地图转换后,工程中存在 Web 地图的完整状态。 随即可对工程进行进一步修改,然后将其打印或导出为常用格式(如 PDF)。当从 Web GIS 应用程序使用 ArcGIS API for JavaScriptArcGIS Web AppBuilderArcGIS Experience Builder 打印地图时,最常使用的是 ConvertWebMapToArcGISProject

有关详细说明、案例和代码示例,请参阅使用 arcpy.mp 打印 Web 地图

语法

ConvertWebMapToArcGISProject (webmap_json, {template_pagx}, {mapframe_name}, {notes_gdb}, {report_template})
参数说明数据类型
webmap_json

The web map for printing in JSON. See the ExportWebMap JSON specification for more information. ArcGIS API for JavaScript, ArcGIS Web AppBuilder and ArcGIS Experience Builder 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 that will be used for templates. Use the format {"id": "<portal-d>"}.

(默认值为 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.

(默认值为 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.

(默认值为 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.

(默认值为 None)

String
返回值
数据类型说明
tuple

返回 Python 命名的 Web 地图和请求属性的元组。

  • ArcGISProject将返回作为函数输出创建的 ArcGISProject 对象。 ArcGISProject 对象在内存中创建。 要在磁盘上创建工程的永久副本,请调用 ArcGISProject 对象上的 saveACopy 函数。
  • DPI将返回从 Web 应用程序导出时所要求的 DPI。
  • outputSizeHeight将返回在 Web 应用程序中指定的影像高度。 可以在执行地图视图导出时使用。
  • outputSizeWidth将返回在 Web 应用程序中指定的影像宽度。 可以在执行地图视图导出时使用。

代码示例

ConvertWebMapToArcGISProject 示例 1

在本示例中,脚本在 Web 地图 JSON 中读取。 ConvertWebMapToArcGISProject 的输出 MapView 对象将导出到 .png 文件。 输出地图不会包含任何页面布局整饰要素(例如标题、图例或比例尺)。

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 示例 2

在本示例中,脚本在 Web 地图 JSON 中读取。 ConvertWebMapToArcGISProject 中的输出 MapView 范围在导出到 .png 文件之前进行了修改。 exportToPNG 函数使用用户定义的 heightwidthworld_filecolor_mode 参数值。 输出地图不会包含任何页面布局整饰要素(例如标题、图例或比例尺)。

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 示例 3

在此示例中,使用了过渡布局模板(.pagx 文件),该模板包含所有可能的服务图层的矢量等效表示。 运行 ConvertWebMapToArcGISProject 函数后,脚本循环遍历输出地图中的所有图层,并从 Web 地图 JSON 中移除所有服务图层,只留下过渡的矢量图层。 随后输出布局将导出为 PDF 或 .png 文件。 本示例还显示了如何将“打印”任务支持的标准参数之外的附加参数 (Georef_info) 从 Web 应用程序传递到 Python 脚本。

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 示例 4

在此示例中,Layer 类中的 updateLayerFromJSON 函数可用于使用 Web 地图 JSON 中动态图层的图层定义更新布局模板中过渡矢量图层的属性(例如,符号系统)。 如果 Web 应用程序允许更改动态图层的符号系统并且您希望将服务图层替换为过渡的矢量数据,但仍保留 Web 应用程序中更新的符号系统,则上述操作将十分有用。

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 示例 5

在本示例中,该脚本分别在 Web 地图 JSON、布局模板以及该 Web 地图将附加到的现有 PDF 中读取。 将 ConvertWebMapToArcGISProject 函数中的输出布局导出为 PDF,再使用 PDFDocument 类将其插入到其他 PDF 中。

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 示例 6

在本例中,使用了已启用空间地图系列的过渡布局模板(.pagx 文件)。 可将与 web 地图范围相交的地图系列索引要素导出到多页 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 示例 7

此示例演示了如何从 web 地图中的要素服务访问所选要素,并将其显示在报表中。 ArcGISProject 类上的 importDocument 函数用于将报表文件 (.rptx) 导入到从 ConvertWebMapToArcGISProject 返回的 ArcGIS Pro 工程中。 默认情况下,报告将仅显示所选要素。 Report 类用于设置报表的数据源。 可以使用 PDFDocument 类将输出布局和报表导出为 PDF 并追加到一起。

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 示例 8

此示例演示了如何从 web 地图中的要素服务访问所选要素,并将其显示在表格框架中。 过渡布局模板(.pagx 文件)中的表格框架使用已在脚本中移除的临时图层。 本示例使用 Python CIM 访问将表格框架的源更新为 web 地图中的图层。

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 示例 9

在本示例中,ImportCredentials 函数用于访问 ArcGIS Server 受保护服务。

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