ConvertWebMapToMapDocument (arcpy.mapping)

摘要

将要打印或导出的 Web 地图(JSON 格式)转换为地图文档。可在最终打印或导出地图文档之前对其进行进一步修改。

讨论

ConvertWebMapToMapDocument 函数将您想要打印或导出的 Web 地图转换为地图文档。文档转换后,地图文档中存在 Web 地图的完整状态。随即可对地图文档进行进一步修改,然后将其最终打印或导出为常用格式(如 PDF)。使用 ArcGIS Web API 从 Web 应用程序打印地图时,最常使用 ConvertWebMapToMapDocument 函数。

ConvertWebMapToMapDocument 函数主要用于需要使用 arcpy.mapping 函数修改或导出 Web 地图的工作流。可以使用 ConvertWebMapToMapDocument 函数处理的部分工作流示例如下:

注注:
通过自定义设置来实现此功能。

ArcGIS for Server 还包括名为 PrintingTools 的地理处理服务。PrintingTools 服务可用于 Web 应用程序中,生成高制图质量的可打印图像。有关 PrintingTools 服务的详细信息,请参阅以下内容:

如果您已经获取了一个为打印操作而准备地图的 Python 脚本后,可以在地理处理脚本工具中封装该脚本。您随后可将脚本工具作为 ArcGIS Server 地理处理服务发布。每个 ArcGIS Web API 都具有一个可用于 Web 应用程序中的打印任务打印任务具有 URL 属性,该属性指向所创建的地理处理服务的 REST URL。有关使用 ArcGIS Web API 的详细信息,请参阅您所偏好的开发平台的帮助。

有关地理处理服务的详细信息,请参阅以下内容:

在 ArcGIS Web API 的地理处理服务中使用 ConvertWebMapToMapDocument 时,脚本工具的参数名称必须与 ArcGIS Web API 打印任务参数相匹配:

参数名称

数据类型

说明

Web_Map_as_JSON

字符串

当地图在 Web 应用程序中显示时,待导出的地图状态的 JSON 表示。通过 ArcGIS Web API(JavaScript、Flex、和 Silverlight),开发人员可以从地图应用程序中轻松获得此 JSON 字符串。

Output_File

文件

输出文件名。文件扩展名取决于格式参数。

格式

字符串

传送打印用地图影像时所使用的格式。接受以下字符串:

  • PNG8(参数留空时的默认值)
  • PNG
  • PDF
  • PNG32
  • JPG
  • GIF
  • EPS
  • SVG
  • SVGZ

Layout_Template

字符串

可以是列表中某个模板的名称,也可以是关键字 MAP_ONLY。选择 MAP_ONLY 或传递空字符串时,输出地图不会包含任何页面布局的周围要素(例如标题、图例和比例尺)。

提示提示:

还可以添加任意数量的附加用户定义参数。将额外的参数传递到自定义打印任务这一功能非常有用,它允许您从 Web 应用程序收集任意数量的额外参数,并将其传递到 Python 脚本中。

从 web 应用程序打印地图时,最常使用 ConvertWebMapToMapDocument 函数。当您使用 ArcGIS Web API 打印任务时,不需要创建 Web 地图 JSON;因为 API 会为您解决这个问题。但是,只有在本地运行脚本之后,才能发布并在 Web API 中使用该脚本。本地运行脚本时,可以使用任何有效的 web 地图 JSON 字符串。要成功运行脚本,可能需要与 web 应用程序返回的字符串类似的 JSON 字符串。请参阅 ExportWebMap 规范来了解对此文本进行格式化的方式。示例字符串如下:

{
    "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"
}

运行脚本工具时,JSON 字符串可复制并粘贴到 Web_Map_as_JSON 输入参数中。但是,必须移除字符串中的换行符,该字符串才能成为有效输入。移除了换行符的 JSON 字符串示例如下:

{"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"}

提示提示:

出于发布目的,由于 ArcGIS Web API 将在 Web 应用程序中提供 Web 地图 JSON,您可将 Web_Map_as_JSON 输入参数留空。如果 Python 脚本的写入方式使其在空白输入时仍能正常执行,则可将 Web_Map_as_JSON 输入参数留空。例如,脚本不会按名称查找 Web 地图图层。如果由于脚本错误而导致脚本在服务器上运行失败,则必须在本地将其修复,然后重新发布到服务器。因此,在发布前最好在本地确认脚本能够执行,这可以通过测试有效的 web 地图 JSON 字符串或使用包含 web 地图 JSON 中的所有要素的调试地图文档来完成。

提示提示:

如前所述,从 ArcGIS Web API 返回的 JSON 字符串包含 Web 地图的完整状态。JSON 字符串中的 layoutOptions 对象保证了进一步讨论,因为它会自动更新可在 template_mxd 中过渡的布局元素。例如,如果 JSON 具有 titleText 设置,且 template_mxd 具有动态文本标题元素,则模板地图文档布局中的标题将使用 titleText 的值进行更新。有关详细信息,请参阅 ExportWebMap 规范layoutOptions 部分。

当您在地理处理服务中封装使用 ConvertWebMapToMapDocument 的 Python 脚本时,您需要确保 ArcGIS for Server 可以看到 Web 应用程序中使用的模板地图文档和数据。最佳做法是使用通过 ArcGIS for Server 注册的文件夹。有关注册数据的详细信息,请参阅以下内容:

在注册的文件夹中制作模板地图文档时,最佳做法是使用相对路径。这样,ArcGIS for Server 就可以在地图文档位置相对的注册文件夹中找到数据。有关详细信息,请参阅引用地图中的数据

警告警告:

使用 ConvertWebMapToMapDocument 时,图层的相对路径必须指向 template_mxd 的路径所在级别、之下的级别或之上一层的级别。

警告警告:

如果选择不使用注册的文件夹,那么模板地图文档和数据将打包复制到服务器。在打包过程中,数据可能会移动,并且重新指向 ConvertWebMapToMapDocument 无法解析的文件夹结构的相对路径。因此,建议使用注册的文件夹。

除了创建自己的模板地图文档之外,还可以使用随软件提供的预先制作的模板。这些模板位于 <installation_directory>\Templates\ExportWebMapTemplates。这些模板包含图例、当前日期动态文本、比例尺和比例文本等地图元素。

默认情况下,Web 应用程序的注释叠加或客户端图像将存储在内存工作空间中。内存工作空间是临时性的,将在关闭应用程序时被删除。要创建包含注释叠加的输出地图文档的永久副本,请先指定 notes_gdb,然后使用合并地图打包地图地理处理工具来创建输出地图文档副本。仅在计划创建输出地图文档永久副本时,才会需要指定 notes_gdb。参阅下面的代码示例 2。如果 Web 地图不包含注释叠加,您可以使用 MapDocument 类的 saveACopy 方法来创建输出地图文档的永久复本。

arcpy.mapping 模块还提供了用于在输出地图文档的布局中控制图例外观的方法。要移除图例项,请参阅 LegendElement 类中的 removeItem 方法。下面列出的高级教程将对此工作流进行说明。要更新图例项,请参阅 LegendElement 类中的 updateItem 方法以及 ListStyleItems 方法。

请确保阅读下列教程。这些教程演示了使用 ConvertWebMapToMapDocument 工作流进行矢量打印和导出的整个过程:创作过渡模板地图文档、创作 Python 脚本、创建地理处理服务、创建 Web 应用程序。

语法

ConvertWebMapToMapDocument (webmap_json, {template_mxd}, {notes_gdb}, {extra_conversion_options})
参数说明数据类型
webmap_json

The web map for printing in JavaScript Object Notation (JSON). See the ExportWebMap JSON specification for more information. The ArcGIS Web APIs (JavaScript, Flex, and Silverlight) allow developers to easily get this JSON string from the web application.

String
template_mxd

A string representing the path and file name to a map document (.mxd) to use as the template for the page layout. The contents of the web map will be inserted into the data frame that was active at the time the template_mxd was saved. Layers in the template_mxd file's active data frame (and all other data frames) will be preserved in the output mapDocument.

(默认值为 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, which is essential if you plan to use the map document for operations that require saving or loading from disk (for example, packaging or consolidating). The path must end with a .gdb or .sde extension.

(默认值为 None)

String
extra_conversion_options

A dictionary of credentials for secured services. This parameter is required if the services in the web map JSON require a user name and password to view. Keys accepted in the dictionary are as follows:

  • SERVER_CONNECTION_FILE
  • WMS_CONNECTION_FILE
  • WMTS_CONNECTION_FILE

An example of key value pairs is as follows:

credentials = {"SERVER_CONNECTION_FILE":r"Z:\ArcGIS2 on MyServer (user).ags", 
               "WMS_CONNECTION_FILE":r"Z:\USA on MyServer.wms"}
result = arcpy.mapping.ConvertWebMapToMapDocument(json, 
                                                  extra_conversion_options=credentials)

Lists of connection files can be used when there are multiple secured services:

agsConnections = [r"Z:\ArcGIS on SecuredServerA (user).ags", 
                  r"Z:\ArcGIS on SecuredServerB (user).ags"]
credentials = {"SERVER_CONNECTION_FILE":agsConnections, 
               "WMS_CONNECTION_FILE":r"Z:\USA on MyServer.wms"}
result = arcpy.mapping.ConvertWebMapToMapDocument(json, 
                                                  extra_conversion_options=credentials)

(默认值为 None)

Dictionary
返回值
数据类型说明
tuple

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

  • mapDocument作为函数输出而创建的地图文档对象。
  • DPI从 Web 应用程序导出时所要求的 DPI。
  • outputSizeHeightWeb 应用程序中指定的图像高度。执行数据视图导出时使用。
  • outputSizeWidthWeb 应用程序中指定的图像宽度。执行数据视图导出时使用。
警告警告:

ConvertWebMapToMapDocument 会在系统的临时文件夹中创建临时地图文档(.mxd 文件)。在 Windows Vista 和 Windows 7 上,该临时文件夹位于 C:\Users\<user name>\AppData\Local\Temp。由用户负责管理此文件夹中的地图文档。要在脚本中删除这些临时地图文档,请参阅以下代码示例中的 clean up 部分。

代码实例

ConvertWebMapToMapDocument 示例 1

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

import arcpy
import os
import uuid

# 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" 
    
# 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
templateMxd = os.path.join(templatePath, Layout_Template + '.mxd')

# 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.mapping.ConvertWebMapToMapDocument(Web_Map_as_JSON, 
                                                  templateMxd)
mxd = result.mapDocument

# 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
arcpy.mapping.ExportToPDF(mxd, 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.mapping.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 - delete the map document reference
filePath = mxd.filePath
del mxd, result
os.remove(filePath)
ConvertWebMapToMapDocument 示例 2

本例中,ConsolidateMap 地理处理工具用于创建包含注释叠加的输出地图文档的永久副本。

import arcpy
import os
import uuid

# The template location in the registered folder
templatePath = '//MyMachine/Austin/WebMap'

# Input web map 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 = "Landscape11x17" 

# Get the requested map document
templateMxd = os.path.join(templatePath, Layout_Template + '.mxd')
    
# Since we are making a permanent copy of the notes overlays, 
# we need to specify a notes geodatabase
notes = os.path.join(arcpy.env.scratchFolder, 'mynotes.gdb')

# Convert the web map to a map document
result = arcpy.mapping.ConvertWebMapToMapDocument(Web_Map_as_JSON, templateMxd, notes)
mxd = result.mapDocument

# Save the web map and notes overlays to a new map document using ConsolidateMap 
arcpy.ConsolidateMap_management(mxd.filePath, 
                                os.path.join(arcpy.env.scratchFolder, 'ConsolidateWebMap'))

# Clean up - delete the map document reference
filePath = mxd.filePath
del mxd, result
os.remove(filePath)
ConvertWebMapToMapDocument 示例 3

本例中,使用了过渡模板地图文档,其中包含所有可能服务图层的矢量等效表示。执行 ConvertWebMapToMapDocument 函数后,该脚本对输出地图文档中的所有图层进行循环,从而移除所有图层(与 Web 地图 JSON 中的服务图层相对应的矢量图层除外)。随后将输出地图文档布局导出为 PDF 或 PNG 格式。

import arcpy
import os
import uuid

# The template location in the registered folder 
templatePath = '//MyComputerName/MyDataStore/USA'

# Input web map 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 = "NorthwesternUSA" 
    
# Get the requested map document
templateMxd = os.path.join(templatePath, Layout_Template + '.mxd')

# Convert the web map to a map document
result = arcpy.mapping.ConvertWebMapToMapDocument(Web_Map_as_JSON, templateMxd)
mxd = result.mapDocument

# Reference the data frame that contains the web map
# Note: ConvertWebMapToMapDocument renames the active dataframe in the template_mxd to "Webmap"
df = arcpy.mapping.ListDataFrames(mxd, 'Webmap')[0]

# Get a list of all service layer names in the map
serviceLayersNames = [slyr.name for slyr in arcpy.mapping.ListLayers(mxd, data_frame=df) 
                      if slyr.isServiceLayer and slyr.visible and not slyr.isGroupLayer]

# Create a list of all possible vector layer names in the map that could have a 
# corresponding service layer
vectorLayersNames = [vlyr.name for vlyr in arcpy.mapping.ListLayers(mxd, data_frame=df) 
                     if not vlyr.isServiceLayer and not vlyr.isGroupLayer]

# Get a list of all vector layers that don't have a corresponding service layer
removeLayerNameList = [vlyrName for vlyrName in vectorLayersNames 
                       if vlyrName not in serviceLayersNames]

# Remove all vector layers that don't have a corresponding service layer
for lyr in arcpy.mapping.ListLayers(mxd, data_frame=df):
    if not lyr.isGroupLayer \
    and not lyr.isServiceLayer \
    and lyr.name in removeLayerNameList \
    and lyr.name in vectorLayersNames:
        arcpy.mapping.RemoveLayer(df, lyr)
                
# Remove all service layers
# This will leave only vector layers that had corresponding service layers
for slyr in arcpy.mapping.ListLayers(mxd, data_frame=df):
    if slyr.isServiceLayer:
        arcpy.mapping.RemoveLayer(df, slyr)
        
# 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 web map
if Format.lower() == 'pdf':
    arcpy.mapping.ExportToPDF(mxd, Output_File) 
elif Format.lower() == 'png':
    arcpy.mapping.ExportToPNG(mxd, Output_File)

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

# Clean up - delete the map document reference
filePath = mxd.filePath
del mxd, result
os.remove(filePath)
ConvertWebMapToMapDocument 示例 4

本例中,使用了过渡模板地图文档,其中包含所有可能服务图层的矢量等效表示。执行 ConvertWebMapToMapDocument 函数后,该脚本对输出地图文档中的所有图层进行循环,从而移除所有图层(与 Web 地图 JSON 中的服务图层相对应的矢量图层除外)。然后使用 DPI,应用 Web 应用程序中指定的 ConvertWebMapToMapDocument 函数返回的输出高度值和输出宽度值将输出地图文档的数据视图导出为 PNG。

import arcpy
import os
import uuid

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

# The template location in the registered folder 
templatePath = '//MyComputerName/MyDataStore/FederalLands'

# Get the template map document
templateMxd = os.path.join(templatePath, 'FederalLands.mxd')

# Convert the web map to a map document
result = arcpy.mapping.ConvertWebMapToMapDocument(Web_Map_as_JSON, templateMxd)
mxd = result.mapDocument

# Reference the data frame that contains the web map
# Note: ConvertWebMapToMapDocument renames the active dataframe in the template_mxd to "Webmap"
df = arcpy.mapping.ListDataFrames(mxd, 'Webmap')[0]

# Get a list of all service layer names in the map
serviceLayersNames = [slyr.name for slyr in arcpy.mapping.ListLayers(mxd, data_frame=df) 
                      if slyr.isServiceLayer and slyr.visible and not slyr.isGroupLayer]

# Create a list of all possible vector layer names in the map that could have a 
# corresponding service layer
vectorLayersNames = [vlyr.name for vlyr in arcpy.mapping.ListLayers(mxd, data_frame=df) 
                     if not vlyr.isServiceLayer and not vlyr.isGroupLayer]

# Get a list of all vector layers that don't have a corresponding service layer
removeLayerNameList = [vlyrName for vlyrName in vectorLayersNames 
                       if vlyrName not in serviceLayersNames]

# Remove all vector layers that don't have a corresponding service layer
for lyr in arcpy.mapping.ListLayers(mxd, data_frame=df):
    if not lyr.isGroupLayer \
    and not lyr.isServiceLayer \
    and lyr.name in removeLayerNameList \
    and lyr.name in vectorLayersNames:
        arcpy.mapping.RemoveLayer(df, lyr)
                
# Remove all service layers
# This will leave only vector layers that had corresponding service layers
for slyr in arcpy.mapping.ListLayers(mxd, data_frame=df):
    if slyr.isServiceLayer:
        arcpy.mapping.RemoveLayer(df, slyr)
        
# 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
arcpy.mapping.ExportToPNG(mxd, Output_File, df, 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 - delete the map document reference
filePath = mxd.filePath
del mxd, result
os.remove(filePath)
ConvertWebMapToMapDocument 示例 5

此例中,用户提供了与在模板地图文档中启用的数据驱动页面对应的页面范围。随后页面范围导出为多页 PDF 文档。

import arcpy
import os
import uuid

# The template location in the registered folder 
templatePath = '//MyComputerName/MyDataStore/WebMap'

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

# Data Driven Page numbers as comma delimited string
DDP_Pages = arcpy.GetParameterAsText(1)
if DDP_Pages == '#' or not DDP_Pages:
    DDP_Pages = "1, 3, 10-13" 

# Get the template map document
templateMxd = os.path.join(templatePath, 'DDP.mxd')

# Convert the WebMap to a map document
result = arcpy.mapping.ConvertWebMapToMapDocument(Web_Map_as_JSON, 
                                                  templateMxd)
mxd = result.mapDocument

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

# Export the WebMap Data Driven Pages to PDF
mxd.dataDrivenPages.exportToPDF(Output_Name, "RANGE", DDP_Pages)

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

# Clean up - delete the map document reference
filePath = mxd.filePath
del mxd, result
os.remove(filePath)
5/10/2014