ConvertWebMapToArcGISProject

Краткая информация

Конвертирует веб-карту (в формате JSON), которую вы хотите напечатать или экспортировать, в объект ArcGISProject. Проект ArcGIS затем можно изменить перед печатью или экспортом.

Обсуждение

После преобразования веб-карты в проект переходят все элементы веб-карты. Затем можно изменить проект перед печатью или экспортом в стандартные форматы, такие как PDF.ConvertWebMapToArcGISProject чаще всего используется при печати карты из веб-ГИС приложения с использованием ArcGIS API for JavaScript, ArcGIS Web AppBuilder или ArcGIS Experience Builder.

Более подробную информацию, сценарии и обсуждения см. в разделе Печать веб-карт с помощью arcpy.mp.

Синтаксис

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 веб-карты и запрашивает свойства:

  • ArcGISProjectБудет возвращен объект ArcGISProject, созданный в результате работы функции. Объект ArcGISProject создается в памяти. Для создания постоянной копии проекта на диске, вызовите функцию saveACopy на объекте ArcGISProject.
  • DPIВозвращается запрошенное разрешение данных, экспортируемых из веб-приложения.
  • outputSizeHeightВозвращается высота изображения, как указано в веб-приложении. Используется при выполнении экспорта вида карты.
  • outputSizeWidthВозвращается ширина изображения, как указано в веб-приложении. Используется при выполнении экспорта вида карты.

Пример кода

ConvertWebMapToArcGISProject, пример 1

В этом примере скрипт считывает веб-карту JSON. Выходной объект MapView из ConvertWebMapToArcGISProject экспортируется в файл .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

В этом примере скрипт считывает веб-карту JSON. Выходной экстент MapView из ConvertWebMapToArcGISProject будет изменен перед экспортом в файл .png. Функция exportToPNG использует заданные пользователем значения для параметров height, width, world_file и color_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 скрипт просматривает все слои выходного документа карты и удаляет все слои, кроме промежуточных векторных, которые соответствуют сервисным слоям в веб-карте JSON. Затем выходная компоновка экспортируется в файл PDF или .png. В этом примере также показано, как добавить дополнительные параметры (Georef_info) из веб-приложения в скрипт 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 используется для обновления свойств (например, символов) промежуточного векторного слоя в шаблоне компоновки с определением динамического слоя из веб-карты JSON. Это удобно, если веб-приложение позволяет менять символы динамических слоев, и вы хотите заменить слои сервиса на промежуточные векторные данные, но все еще видите обновленные символы из веб-приложения.

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

В этом примере скрипт считывает веб-карту JSON, выходной формат, шаблон компоновки и существующие документы PDF, к которым будет присоединена веб-карта. Выходная компоновка из функции ConvertWebMapToArcGISProject экспортируется в PDF, затем включается в другие файлы PDF с помощью класса PDFDocument.

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), для которого включена функция пространственные серии карт. Объекты индексирования многостраничных карт, которые пересекают экстент веб-карт, экспортируются в многостраничный 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

В этом примере показано, как получить доступ к выбранным объектам из сервиса объектов на веб-карте и отобразить их в отчете. Функция importDocument в классе ArcGISProject используется для импорта файла отчета (.rptx) в проект ArcGIS Pro, который возвращается от ConvertWebMapToArcGISProject. По умолчанию в отчете отображаются только выбранные объекты. Класс Report использует для установки источник данных отчета. Выходная компоновка и отчет экспортируются как файлы PDF и соединяются друг с другом с помощью класса PDFDocument.

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

В этом примере показано, как получить доступ к выбранным объектам из сервиса объектов на веб-карте и отобразить их в Фрейме таблицы. Фрейм таблицы в промежуточном шаблоне компоновки (файл.pagx) использует временный слой, который удаляется в скрипте. В этом примере используется Python CIM access для обновления исходного фрейма таблицы до слоя с веб-карты.

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, пример 4

В этом примере функция 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