ConvertWebMapToArcGISProject

摘要

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

说明

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

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

语法

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

以 JSON 格式打印的 Web 地图。有关详细信息,请参阅 ExportWebMapJSON 规范ArcGIS API for JavaScriptArcGIS Web AppBuilder 允许开发者从 Web 应用程序中获取此 JSON 字符串。

String
template_pagx

用于表示用作页面布局模板的布局文件 (.pagx) 的路径和文件名的字符串。Web 地图在 ArcGIS 工程中转换为新地图。布局上的 2D 地图框将引用新创建的地图。有关详细信息,请参阅 mapframe_name 参数。template_pagx 文件的 web 地图地图框(以及所有其他地图框)中的图层将保留在输出 ArcGISProject 中。如果未指定 template_pagx,则使用地图对象的 defaultView 函数来访问 Web 地图的 MapView。在 MapView Web 地图打印工作流中,输出文件不会包含任何布局整饰要素(如标题、图例、比例尺、总览图框等)。

(默认值为 None)

String
mapframe_name

表示布局上地图框名称的字符串,其源将更新为指向包含 Web 地图 JSON 的新建地图。如果布局中只有一个地图框,则默认情况下将用于引用 Web 地图。如果布局中有多个地图框,并且省略此参数,则使用名为 WEBMAP_MAP_FRAME 的地图框。或者,可以指定用户定义的 mapframe_name。如果存在多个地图框,但未找到名为 WEBMAP_MAP_FRAME 的地图框,且未指定 mapframe_name,则该函数将抛出一条错误消息。

(默认值为 None)

String
notes_gdb

用于表示新建或现有文件地理数据库或现有企业级地理数据库连接(其中应写入图形要素)的路径的字符串。只有在 Web 地图 JSON 的图形要素需要永久保存时,此参数才可用。大多数情况下,并不需要此参数,因为将使用临时内存工作空间存储图形要素。此参数可用于将图形要素保存至永续性储存体。路径必须以 .gdb.sde 扩展名为结尾。

(默认值为 None)

String
返回值
数据类型说明
tuple

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

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

代码示例

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

在此示例中,updateLayerFromJSON 类中的 Layer 函数可用于使用 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.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 示例 7

此示例演示了如何从 web 地图中的要素服务访问所选要素,并将其显示在报表中。ArcGISProject 类上的 importDocument 函数用于将报表文件 (.rptx) 导入到从 ConvertWebMapToArcGISProject 返回的 ArcGIS Pro 工程中。默认情况下,报告将仅显示所选要素。报告类用于设置报表的数据源。可以使用 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

在本示例中,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