Layout

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

Объект Layout ссылается на одностраничную компоновку в проекте ArcGIS Pro (.aprx). Он предоставляет доступ к общим свойствам, таким как размер страницы и различные методы экспорта.

Обсуждение

Проект ArcGIS Pro может содержать компоновки из нескольких страниц. Компоновки доступны с помощью метода listLayouts для объекта ArcGISProject, он возвращает список Python объектов Layout. Важно, чтобы у каждой компоновки было свое уникальное имя, благодаря чему на нее можно ссылаться по ее name.

Метод listElements обеспечивает доступ ко всем элементам компоновки страницы: GraphicElement, GroupElement, LegendElement, MapFrameElement, MapSurroundElement, PictureElement и TextElement.

В объекте Layout вы можете получить доступ к ряду методов exportTo. Используйте методы экспорта Layout, если вы хотите экспортировать всю страницу компоновки. Также имеется подобный набор методов экспорта в классе MapFrame, если вы хотите экспортировать содержимое только одного фрейма данных.

Компоновка может содержать один MapSeries. Если свойство mapSeries возвращает None, серии карт в компоновке не создаются. Вы можете также проверить, являются ли серии карт enabled, перед тем, как изменять их свойства.

Метод createLayout на объекте ArcGISProject позволяет полностью автоматизировать создание компоновки. Когда компоновка создана, появляется множество дополнительных методов создания различных типов элементов компоновки. Объект layout имеет два метода для создания элементов, которые могут существовать только в компоновке. Это createMapFrame и createMapSurroundElement. Объект ArcGISProject включает дополнительные методы создания, которые позволяют создавать элементы в компоновке или на графическом слое в map. Это методы createGraphicElement, createGroupElement, createPictureElement, createPredefinedGraphicElement и createTextElement.

Метод openView позволяет открыть новую панель просмотра компоновки. В настоящее время нет способов определить, открыт ли уже вид, или активен ли ваш вид компоновки, поскольку запросы к видам невозможны. Что вы можете сделать, это использовать метод closeViews для объекта ArcGISProject и вызвать openView в компоновке. Это откроет и активирует компоновку, она получит необходимую область и фокус.

Примечание:

Методы openView и closeViews работают только для скриптов, запускаемых из приложения. Автономные скрипты не могут получить доступ к панелям видов.

Свойства

СвойствоОписаниеТип данных
mapSeries
(только чтение)

Возвращает объект MapSeries, если включена серия карт. Он возвращает NoneType, если серия карт не существует или это серия карт закладок.

MapSeries
metadata
(чтение и запись)

Получите или настройте информацию о классе Metadata.

Примечание:
Установка метаданных зависит от значения свойства isReadOnly.

Metadata
name
(чтение и запись)

Имя компоновки. Является важно, чтобы каждый фрейм данных имел уникальное имя, которое потом используется в ссылках на фрейм.

String
pageHeight
(чтение и запись)

Высота компоновки страницы базируется на текущих pageUnits.

Double
pageUnits
(чтение и запись)

Единицы страницы компоновки. Ниже приведен список допустимых строк при установке единиц страницы.

  • CENTIMETERСантиметр
  • INCHДюйм
  • MILLIMETERМиллиметр
  • POINTТочка
String
pageWidth
(чтение и запись)

Ширина компоновки страницы базируется на текущих pageUnits.

Double
URI
(только чтение)

Universal Resource Indicator для компоновки. Это уникальный идентификатор компоновки в проекте, который иногда требуется при использовании доступа Python CIM. После добавления компоновки и установления URI значение со временем не меняется. Например, если вы измените имя компоновки, URI не изменится.

String

Обзор метода

МетодОписание
createBookmarkMapSeries (mapframe, {bookmarks})

Этот метод создает новый элемент BookmarkMapSeries в компоновке.

createMapFrame (geometry, {map}, {name})

Метод createMapFrame создает элемент MapFrame в компоновке.

createMapSurroundElement (geometry, mapsurround_type, {mapframe}, {style_item}, {name})

Метод createMapSurroundElement создает MapSurroundElement в компоновке.

createSpatialMapSeries (mapframe, index_layer, name_field, {sort_field})

Этот метод создает серию пространственных карт MapSeries object для компоновки.

deleteElement (element)

Функция deleteElement удаляет элемент компоновки.

exportToAIX (out_aix, {resolution}, {image_quality}, {compress_vector_graphics}, {image_compression}, {jpeg_compression_quality}, {embed_fonts}, {embed_color_profile}, {clip_to_elements}, {keep_layout_background}, {convert_markers})

Экспортирует Компоновку в формат Adobe Illustrator Exchange (AIX). Файлы AIX можно использовать с дополнительным модулем ArcGIS Maps for Adobe Creative Cloud или Adobe Illustrator.

exportToBMP (out_bmp, {resolution}, {bmp_color_mode}, {bmp_image_compression}, {embed_color_profile}, {clip_to_elements})

Экспортирует Компоновку в формат Microsoft Windows Bitmap (BMP).

exportToEMF (out_emf, {resolution}, {image_quality}, {output_as_image}, {clip_to_elements}, {convert_markers})

Экспортирует Компоновку в файл формата Enhanced Metafile (EMF).

exportToEPS (out_eps, {resolution}, {image_compression}, {image_quality}, {embed_fonts}, {output_as_image}, {clip_to_elements}, {convert_markers})

Экспортирует Компоновку в файл формата Encapsulated PostScript (EPS).

exportToGIF (out_gif, {resolution}, {gif_color_mode}, {clip_to_elements})

Экспортирует Компоновку в Graphic Interchange Format (GIF).

exportToJPEG (out_jpg, {resolution}, {jpeg_color_mode}, {jpeg_quality}, {embed_color_profile}, {clip_to_elements})

Экспортирует Компоновку в файл формата Joint Photographic Experts Group (JPEG).

exportToPAGX (out_pagx)

Экспортирует Компоновку в файл страницы (.pagx).

exportToPDF (out_pdf, {resolution}, {image_quality}, {compress_vector_graphics}, {image_compression}, {embed_fonts}, {layers_attributes}, {georef_info}, {jpeg_compression_quality}, {clip_to_elements}, {output_as_image}, {embed_color_profile}, {pdf_accessibility}, {keep_layout_background}, {convert_markers}, {simulate_overprint})

Экспорт Компоновки в Portable Document Format (PDF).

exportToPNG (out_png, {resolution}, {color_mode}, {transparent_background}, {embed_color_profile}, {clip_to_elements})

Экспортирует Компоновку в файл формата Portable Network Graphics (PNG).

exportToSVG (out_svg, {resolution}, {compress_to_svgz}, {image_quality}, {embed_fonts}, {output_as_image}, {clip_to_elements}, {convert_markers})

Экспортирует Компоновку в формат Scalable Vector Graphics format (SVG).

exportToTGA (out_tga, {resolution}, {color_mode}, {transparent_background}, {clip_to_elements})

Экспортирует Компоновку в формат Truevision Graphics Adapter (TGA).

exportToTIFF (out_tif, {resolution}, {color_mode}, {tiff_compression}, {jpeg_compression_quality}, {transparent_background}, {embed_color_profile}, {clip_to_elements}, {world_file}, {geoTIFF_tags}, {georef_mapframe})

Экспортирует Компоновку в файл Tagged Image File Format (TIFF).

getDefinition (cim_version)

Получает определение компоновки CIM.

listElements ({element_type}, {wildcard})

Возвращает список Python элементов компоновки страницы, который существует а объекте Layout.

openView ()

Открывает и активизирует новую панель вида компоновки в приложении.

setDefinition (definition_object)

Настраивает определение компоновки CIM.

Методы

createBookmarkMapSeries (mapframe, {bookmarks})
ПараметрОписаниеТип данных
mapframe

A MapFrame that will have its camera settings driven by the information persisted in the bookmarks provided.

MapFrame
bookmarks
[bookmarks,...]

A list of Bookmark objects from either a single map, or multiple maps. If a list is not provided, the bookmarks that belong to the map associated with the map frame will be used instead.

List
Возвращаемое значение
Тип данныхОписание
Object

Возвращает ссылку на новый объект BookmarkMapSeries.

Страница серий карт закладок создается для каждой закладки. Обратитесь к разделу справки BookmarkMapSeries для получения дополнительной информации и примеров кода.

createMapFrame (geometry, {map}, {name})
ПараметрОписаниеТип данных
geometry

The appropriate Point, or Polygon object that will be used to construct the element using page units.

Object
map

The Map associated with the MapFrame. If the default value of None is used, it can be changed at a later time.

(Значение по умолчанию — None)

Map
name

An optional string that represents the name of the new MapFrame element. If a name is not provided, the default name value will follow the automatic sequencing nomenclature, for example, Map Frame, Map Frame 1, Map Frame 2, and so on.

String
Возвращаемое значение
Тип данныхОписание
MapFrame

Если указана переменная, она будет ссылаться на вновь возращенный объект MapFrame.

Фрейм карты не обязательно должен быть связан с картой при создании, и значением по умолчанию является None. Если элемент создается с помощью точечной геометрии, местоположение точки будет содержать позицию anchor, а размер будет задан по умолчанию. Позже вы можете изменить размер элемента, используя свойства elementWidth и elementHeight.

Обратитесь к разделу справки по классу MapFrame для получения дополнительной информации и примеров кода.

createMapSurroundElement (geometry, mapsurround_type, {mapframe}, {style_item}, {name})
ПараметрОписаниеТип данных
geometry

A Point or a Polygon object that will be used to construct the element. The map surround types have different anchor locations so if you are creating an element with a point geometry, you will need to consider positioning relative to the default anchor location.

Object
mapsurround_type

A string that represents the map surround element that will be created

  • LEGENDA legend element will be created.
  • NORTH_ARROWA north arrow element will be created.
  • SCALE_BARA scale bar element will be created.
String
mapframe

The MapFrame element that will be associated with the map surround. If the default value of None is used, it can be changed at a later time.

(Значение по умолчанию — None)

MapFrame
style_item

An optional reference to a StyleItem value. It must match the mapsuround_type input parameter. If a style_item value is not provided, a default style will be applied.

String
name

An optional string that represents the name of the new MapSurroundElement. If a name is not provided, the default name value will follow the automatic sequencing nomenclature, for example, North Arrow, North Arrow 1, North Arrow 2, and so on.

String
Возвращаемое значение
Тип данныхОписание
MapSurroundElement

Возвращает ссылку на новый объект MapSurroundElement или LegendElement.

Если элемент создается с помощью точечной геометрии, местоположение точки будет содержать позицию anchor, а размер будет задан по умолчанию. Позже вы можете изменить размер элемента, используя свойства elementWidth и elementHeight.

Этот метод возвращает ссылку на новый класс MapSurroundElement или LegendElement. Положение якоря по умолчанию зависит от типа зарамочного оформления карты, но его можно изменить после добавления нового элемента на компоновку с помощью метода setAnchor.

Обратитесь к разделу справки по классу MapSurroundElement или LegendElement для получения дополнительной информации и примеров кода.

createSpatialMapSeries (mapframe, index_layer, name_field, {sort_field})
ПараметрОписаниеТип данных
mapframe

A MapFrame object that has an associated map that includes the index layer needed for creating the spatial map series pages.

MapFrame
index_layer

The index Layer object needed for the extents and attribute information for each page.

(Значение по умолчанию — None)

Layer
name_field

The field name of the field used to control the name of each page in the map series. Ideally, all field values are unique so each page can be uniquely identified.

String
sort_field

The name of the field that will be used to sort the map series pages.

String
Возвращаемое значение
Тип данныхОписание
MapSeries

Возвращает ссылку на новый объект MapSeries.

Для каждого объекта в индексном слое создается страница серии карт. См. раздел справки MapSeries с дополнительной информацией и примерами кода по серии карт.

deleteElement (element)
ПараметрОписаниеТип данных
element

An object that represents a layout element to be deleted.

Object

Элемент удаляется из компоновки навсегда. Удаление элемента может повлиять на другие элементы. Например, если вы удалите фрейм карты, на который ссылается другое зарамочное оформление карты, это повлияет на эти элементы. Чтобы удалить несколько элементов, выполните итерацию по указанному списку и удаляйте по одному за раз.

Примечание:

Если вы выполняете итерацию по всем элементам, вы должны удалить элементы группы в обратном порядке, в противном случае, если вы удалите родительский элемент группы, а затем попытаетесь удалить дочерний элемент группы, возникнет ошибка, поскольку ссылка на дочерний элемент больше не существует.

exportToAIX (out_aix, {resolution}, {image_quality}, {compress_vector_graphics}, {image_compression}, {jpeg_compression_quality}, {embed_fonts}, {embed_color_profile}, {clip_to_elements}, {keep_layout_background}, {convert_markers})
ПараметрОписаниеТип данных
out_aix

A string that represents the path and file name for the output export file.

String
resolution

A number that defines the resolution of the export file in dots per inch (dpi).

(Значение по умолчанию — 300)

Integer
image_quality

A string that specifies output image quality, the draw resolution of map layers that draw as rasters.

  • BESTAn output image quality resample ratio of 1
  • BETTERAn output image quality resample ratio of 2
  • NORMALAn output image quality resample ratio of 3
  • FASTERAn output image quality resample ratio of 4
  • FASTESTAn output image quality resample ratio of 5

(Значение по умолчанию — BEST)

String
compress_vector_graphics

A Boolean that controls compression of vector and text portions of the output file. Image compression is defined separately.

(Значение по умолчанию — True)

Boolean
image_compression

A string that specifies the compression scheme used to compress image or raster data in the output file.

  • ADAPTIVEAutomatically selects the best compression type for each image on the page. JPEG will be used for large images with many unique colors. DEFLATE will be used for all other images.
  • DEFLATEA lossless data compression.
  • JPEGA lossy data compression.
  • JPEG2000Offers higher quality compression with smaller file size than JPEG. This compression is lossless if jpeg_compression_quality is set to 100.
  • LZWLempel-Ziv-Welch, a lossless data compression.
  • NONECompression is not applied.
  • RLERun-length encoded compression.

(Значение по умолчанию — ADAPTIVE)

String
jpeg_compression_quality

A number that controls compression quality value when image_compression is set to ADAPTIVE or JPEG. The valid range is 1 through 100. A jpeg_compression_quality of 100 provides the best-quality images but creates large export files. The recommended range is between 70 and 90.

(Значение по умолчанию — 80)

Integer
embed_fonts

A Boolean that controls the embedding of fonts in the export file. Font embedding allows text and character markers to be displayed correctly when the document is viewed on a computer that does not have the necessary fonts installed.

(Значение по умолчанию — True)

Boolean
embed_color_profile

If set to True, color profile information is embedded in the image's metadata.

(Значение по умолчанию — True)

Boolean
clip_to_elements

If set to True, the layout is clipped to the smallest bounding box that includes all layout elements.

(Значение по умолчанию — False)

Boolean
keep_layout_background

If set to True, the layout's white background will be kept.

(Значение по умолчанию — False)

Boolean
convert_markers

A Boolean that controls the conversion of character-based marker symbols to polygons. This allows the symbols to appear correctly if the symbol font is not available or cannot be embedded. However, setting this parameter to True disables font embedding for all character-based marker symbols, which can result in a change in their appearance.

(Значение по умолчанию — False)

Boolean

AIX - это файл Adobe Illustrator Exchange, экспортированный из ArcGIS, который будет использоваться с надстройкой ArcGIS Maps for Adobe Creative Cloud. При использовании с плагином векторное и растровое содержание карты преобразуется в редактируемые многослойные графические объекты, которые удобно редактировать в Adobe Illustrator. После открытия в Illustrator их можно использовать для профессионального графического дизайна или завершающего этапа работ по подготовке карты, а также дальнейшей передачи этих данных в другие приложения Adobe Creative Cloud.

exportToBMP (out_bmp, {resolution}, {bmp_color_mode}, {bmp_image_compression}, {embed_color_profile}, {clip_to_elements})
ПараметрОписаниеТип данных
out_bmp

A string that represents the path and file name for the output export file.

String
resolution

A number that defines the resolution of the export file in dots per inch (dpi).

(Значение по умолчанию — 96)

Integer
bmp_color_mode

This value specifies the number of bits used to describe color.

  • 8-BIT_ADAPTIVE_PALETTE8-bit adaptive palette
  • 8-BIT_GRAYSCALE8-bit grayscale
  • 24-BIT_TRUE_COLOR24-bit true color

(Значение по умолчанию — 24-BIT_TRUE_COLOR)

String
bmp_image_compression

A string that specifies the compression scheme used to compress image or raster data in the output file. This option only applies to 8-bit bmp_color_mode options.

  • NONECompression is not applied.
  • RLERun-length encoded compression.

(Значение по умолчанию — NONE)

String
embed_color_profile

If set to True, color profile information is embedded in the image's metadata.

(Значение по умолчанию — True)

Boolean
clip_to_elements

If set to True, the layout is clipped to the smallest bounding box that includes all layout elements.

(Значение по умолчанию — False)

Boolean

Формат BMP является "родным" форматом растровых изображений Windows. Файлы BMP могут хранить данных в пикселах в разной битовой глубине. Обычно файлы в формате BMP получаются гораздо больше, чем JPEG или PNG.

exportToEMF (out_emf, {resolution}, {image_quality}, {output_as_image}, {clip_to_elements}, {convert_markers})
ПараметрОписаниеТип данных
out_emf

A string that represents the system path and file name for the output export file.

String
resolution

A number that defines the resolution of the export file in dots per inch (dpi).

(Значение по умолчанию — 96)

Integer
image_quality

A string that specifies output image quality, the draw resolution of map layers that draw as rasters.

  • BESTAn output image quality resample ratio of 1
  • BETTERAn output image quality resample ratio of 2
  • NORMALAn output image quality resample ratio of 3
  • FASTERAn output image quality resample ratio of 4
  • FASTESTAn output image quality resample ratio of 5

(Значение по умолчанию — BEST)

String
output_as_image

If set to True, vector content can be saved as an image. Selecting this option for maps or layouts that contain vector layers with a high density of vertices can reduce the output file size. When exporting to PDF and this option is set to True, you cannot view PDF layers in the output.

(Значение по умолчанию — False)

Boolean
clip_to_elements

If set to True, the layout is clipped to the smallest bounding box that includes all layout elements.

(Значение по умолчанию — False)

Boolean
convert_markers

A Boolean that controls the conversion of character-based marker symbols to polygons. This allows the symbols to appear correctly if the symbol font is not available or cannot be embedded. However, setting this parameter to True disables font embedding for all character-based marker symbols, which can result in a change in their appearance.

(Значение по умолчанию — False)

Boolean

EMF – это собственные графические файлы Windows, которые могут содержать комбинацию векторных и растровых данных. Они удобны для включения в документы Windows, т.к. размер изображений, содержащихся в векторных частях EMF, изменяется без потери качества. Но так как EMF не поддерживает встроенные шрифты и является эксклюзивным форматом Windows, его редко используют в качестве обменного формата.

exportToEPS (out_eps, {resolution}, {image_compression}, {image_quality}, {embed_fonts}, {output_as_image}, {clip_to_elements}, {convert_markers})
ПараметрОписаниеТип данных
out_eps

A string that represents the system path and file name for the output export file.

String
resolution

A number that defines the resolution of the export file in dots per inch (dpi).

(Значение по умолчанию — 96)

Integer
image_compression

A string that specifies the compression scheme used to compress image or raster data in the output file.

  • DEFLATEA lossless data compression.
  • LZWLempel-Ziv-Welch, a lossless data compression.
  • NONECompression is not applied.
  • RLERun-length encoded compression.

(Значение по умолчанию — DEFLATE)

String
image_quality

A string that specifies output image quality, the draw resolution of map layers that draw as rasters.

  • BESTAn output image quality resample ratio of 1.
  • BETTERAn output image quality resample ratio of 2.
  • NORMALAn output image quality resample ratio of 3.
  • FASTERAn output image quality resample ratio of 4.
  • FASTESTAn output image quality resample ratio of 5.

(Значение по умолчанию — BEST)

String
embed_fonts

A Boolean that controls the embedding of fonts in the export file. Font embedding allows text and character markers to be displayed correctly when the document is viewed on a computer that does not have the necessary fonts installed.

(Значение по умолчанию — True)

Boolean
output_as_image

If set to True, vector content can be saved as an image. Selecting this option for maps or layouts that contain vector layers with a high density of vertices can reduce the output file size. When exporting to PDF and this option is set to True, you cannot view PDF layers in the output.

(Значение по умолчанию — False)

Boolean
clip_to_elements

If set to True, the layout is clipped to the smallest bounding box that includes all layout elements.

(Значение по умолчанию — False)

Boolean
convert_markers

A Boolean that controls the conversion of character-based marker symbols to polygons. This allows the symbols to appear correctly if the symbol font is not available or cannot be embedded. However, setting this parameter to True disables font embedding for all character-based marker symbols, which can result in a change in their appearance.

(Значение по умолчанию — False)

Boolean

Файлы EPS используют страницы описательного языка PostScript для описания векторных и растровых объектов. PostScript является стандартом печатной промышленности для графических файлов, картографии и вывода на печать. Файлы EPS могут редактироваться во многих графических приложениях или размещаться как графические элементы в большинстве приложений для компоновки. Файлы EPS поддерживают встроенные шрифты, поэтому те пользователи, у которых не установлены шрифты Esri, все равно могут просматривать изображения с корректными символами.

exportToGIF (out_gif, {resolution}, {gif_color_mode}, {clip_to_elements})
ПараметрОписаниеТип данных
out_gif

A string that represents the system path and file name for the output export file.

String
resolution

A number that defines the resolution of the export file in dots per inch (dpi).

(Значение по умолчанию — 96)

Integer
gif_color_mode

This value specifies the number of bits used to describe color.

  • 8-BIT_ADAPTIVE_PALETTE8-bit adaptive palette
  • 8-BIT_GRAYSCALE8-bit grayscale

(Значение по умолчанию — 8-BIT_ADAPTIVE_PALETTE)

String
clip_to_elements

If set to True, the layout is clipped to the smallest bounding box that includes all layout elements.

(Значение по умолчанию — False)

Boolean

GIF – стандартный растровый формат, используемый в Интернете. Файлы GIF не могут содержать более 256 цветов (8 бит на пиксел), что вместе со сжатием без потерь делает их меньше, чем файлы других форматов.

exportToJPEG (out_jpg, {resolution}, {jpeg_color_mode}, {jpeg_quality}, {embed_color_profile}, {clip_to_elements})
ПараметрОписаниеТип данных
out_jpg

A string that represents the path and file name of the output export file.

String
resolution

A number that defines the resolution of the export file in dots per inch (dpi).

(Значение по умолчанию — 96)

Integer
jpeg_color_mode

This value specifies the number of bits used to describe color.

  • 8-BIT_GRAYSCALE8-bit grayscale
  • 24-BIT_TRUE_COLOR24-bit true color

(Значение по умолчанию — 24-BIT_TRUE_COLOR)

String
jpeg_quality

This value (0–100) controls the amount of compression applied to the output image. With a JPEG image, quality is adversely affected the more compression is applied. A higher quality (highest = 100) setting will produce sharper images and larger file sizes. A lower quality setting will produce more image artifacts and smaller files.

(Значение по умолчанию — 80)

Integer
embed_color_profile

If set to True, color profile information is embedded in the image's metadata.

(Значение по умолчанию — True)

Boolean
clip_to_elements

If set to True, the layout is clipped to the smallest bounding box that includes all layout elements.

(Значение по умолчанию — False)

Boolean

JPEG – это сжатые графические файлы. Они поддерживают 24-битовый цвет и их часто выбирают для использования в Интернет, так как размер JPEG-файла обычно меньше, чем у аналогичных файлов других форматов изображений. Но алгоритм сжатия JPEG выполняется с потерями и не рекомендуется для многих картографических изображений, так как линейные рисунки, текст и значки приобретают артефакты сжатия. Так что PNG для картографических изображений подходит лучше всего.

exportToPAGX (out_pagx)
ПараметрОписаниеТип данных
out_pagx

A string used to save a layout to a page file (.pagx).

String

Этот метод полезен, если вы хотите сохранить компоновку в файл страницы, который впоследствии можно будет импортировать в проект с помощью метода ArcGISProject importDocument.

exportToPDF (out_pdf, {resolution}, {image_quality}, {compress_vector_graphics}, {image_compression}, {embed_fonts}, {layers_attributes}, {georef_info}, {jpeg_compression_quality}, {clip_to_elements}, {output_as_image}, {embed_color_profile}, {pdf_accessibility}, {keep_layout_background}, {convert_markers}, {simulate_overprint})
ПараметрОписаниеТип данных
out_pdf

A string that represents the path and file name for the output export file.

String
resolution

A number that defines the resolution of the export file in dots per inch (dpi).

(Значение по умолчанию — 300)

Integer
image_quality

A string that specifies output image quality, the draw resolution of map layers that draw as rasters.

  • BESTAn output image quality resample ratio of 1
  • BETTERAn output image quality resample ratio of 2
  • NORMALAn output image quality resample ratio of 3
  • FASTERAn output image quality resample ratio of 4
  • FASTESTAn output image quality resample ratio of 5

(Значение по умолчанию — BEST)

String
compress_vector_graphics

A Boolean that controls compression of vector and text portions of the output file. Image compression is defined separately.

(Значение по умолчанию — True)

Boolean
image_compression

A string that specifies the compression scheme used to compress image or raster data in the output file.

  • ADAPTIVEAutomatically selects the best compression type for each image on the page. JPEG will be used for large images with many unique colors. DEFLATE will be used for all other images.
  • DEFLATEA lossless data compression.
  • JPEGA lossy data compression.
  • JPEG2000Offers higher quality compression with smaller file size than JPEG. This compression is lossless if jpeg_compression_quality is set to 100.
  • LZWLempel-Ziv-Welch, a lossless data compression.
  • NONECompression is not applied.
  • RLERun-length encoded compression.

(Значение по умолчанию — ADAPTIVE)

String
embed_fonts

A Boolean that controls the embedding of fonts in the export file. Font embedding allows text and character markers to be displayed correctly when the document is viewed on a computer that does not have the necessary fonts installed.

(Значение по умолчанию — True)

Boolean
layers_attributes

A string that specifies whether the PDF layer and PDF object data (attributes) will be included in the export file.

  • LAYERS_ONLYExport PDF layers only
  • LAYERS_AND_ATTRIBUTESExport PDF layers and feature attributes
  • NONENone

(Значение по умолчанию — LAYERS_ONLY)

String
georef_info

A Boolean that enables the export of coordinate system information for each data frame into the output PDF file.

(Значение по умолчанию — True)

Boolean
jpeg_compression_quality

A number that controls compression quality value when image_compression is set to ADAPTIVE or JPEG. The valid range is 1 through 100. A jpeg_compression_quality of 100 provides the best quality images but creates large export files. The recommended range is between 70 and 90.

(Значение по умолчанию — 80)

Integer
clip_to_elements

If set to True, the layout is clipped to the smallest bounding box that includes all layout elements.

(Значение по умолчанию — False)

Boolean
output_as_image

If set to True, vector content can be saved as an image. Selecting this option for maps or layouts that contain vector layers with a high density of vertices can reduce the output file size. When exporting to PDF and this option is set to True, you cannot view PDF layers in the output.

(Значение по умолчанию — False)

Boolean
embed_color_profile

If set to True, color profile information is embedded in the image's metadata.

(Значение по умолчанию — True)

Boolean
pdf_accessibility

Output a tagged PDF file where text can be read by screen readers or other assistive technology. A tagged PDF file can include alt text—a text description of a graphic element that a screen reader uses to describe the element—for map frames, pictures, and chart frames. Alt text is added in the Element Pane for each element.

(Значение по умолчанию — False)

Boolean
keep_layout_background

If set to True, the white background will be included in the export.

(Значение по умолчанию — True)

Boolean
convert_markers

A Boolean that controls the conversion of character-based marker symbols to polygons. This allows the symbols to appear correctly if the symbol font is not available or cannot be embedded. However, setting this parameter to True disables font embedding for all character-based marker symbols, which can result in a change in their appearance.

(Значение по умолчанию — False)

Boolean
simulate_overprint

Sometimes called soft proofing, simulating overprinting shows a representation of how overlapping areas of ink will appear when printed on a page. You set up overprinting on symbol layers.

(Значение по умолчанию — False)

Boolean

PDF формат создан с учетом возможности просмотра и печати файлов на разных платформах. Эти файлы часто используются для распространения документов через Интернет. Теперь этот формат стал официальным стандартом ISO для обмена документацией. Файлы PDF можно редактировать во многих графических приложениях, с сохранением геопространственной информации, аннотаций, надписей и атрибутов пространственных объектов. Экспорт PDF поддерживает встроенные шрифты, поэтому, даже если у пользователей не установлены шрифты Esri, символы все равно будут отображаться корректно.

Посмотрите класс PDFDocument, чтобы узнать более подробно о том, как работать в файлами PDF, в том числе, выполнять операции присоединения, вставки и настройки свойств.

exportToPNG (out_png, {resolution}, {color_mode}, {transparent_background}, {embed_color_profile}, {clip_to_elements})
ПараметрОписаниеТип данных
out_png

A string that represents the path and file name of the output export file.

String
resolution

A number that defines the resolution of the export file in dots per inch (dpi).

(Значение по умолчанию — 96)

Integer
color_mode

This value specifies the number of bits used to describe color.

  • 8-BIT_ADAPTIVE_PALETTE8-bit adaptive palette
  • 8-BIT_GRAYSCALE8-bit grayscale
  • 24-BIT_TRUE_COLOR24-bit true color
  • 32-BIT_WITH_ALPHA32-bit with alpha

(Значение по умолчанию — 32-BIT_WITH_ALPHA)

String
transparent_background

If set to True, the white page background is set to transparent.

(Значение по умолчанию — False)

Boolean
embed_color_profile

If set to True, color profile information is embedded in the image's metadata.

(Значение по умолчанию — True)

Boolean
clip_to_elements

If set to True, the layout is clipped to the smallest bounding box that includes all layout elements.

(Значение по умолчанию — False)

Boolean

Файл PNG – это универсальный растровый формат, который может отображаться в веб-браузерах и поддерживает вставку в другие документы. Он поддерживает большую битовую глубину цвета и использует сжатие без потерь. Для карт часто лучше всего подходит формат PNG, так как сжатие без потерь обеспечивает читаемость текста и линий, препятствуя возникновению артефактов сжатия, которые могут возникать в формате JPEG. В файлах PNG можно задавать цвет прозрачности.

exportToSVG (out_svg, {resolution}, {compress_to_svgz}, {image_quality}, {embed_fonts}, {output_as_image}, {clip_to_elements}, {convert_markers})
ПараметрОписаниеТип данных
out_svg

A string that represents the path and file name for the output export file.

String
resolution

A number that defines the resolution of the export file in dots per inch (dpi).

(Значение по умолчанию — 96)

Integer
compress_to_svgz

If set to True, the output is compressed.

(Значение по умолчанию — False)

Boolean
image_quality

A string that specifies output image quality, the draw resolution of map layers that draw as rasters.

  • BESTAn output image quality resample ratio of 1.
  • BETTERAn output image quality resample ratio of 2.
  • NORMALAn output image quality resample ratio of 3.
  • FASTERAn output image quality resample ratio of 4.
  • FASTESTAn output image quality resample ratio of 5.

(Значение по умолчанию — BEST)

String
embed_fonts

A Boolean that controls the embedding of fonts in the export file. Font embedding allows text and character markers to be displayed correctly when the document is viewed on a computer that does not have the necessary fonts installed.

(Значение по умолчанию — True)

Boolean
output_as_image

If set to True, vector content can be saved as an image. Selecting this option for maps or layouts that contain vector layers with a high density of vertices can reduce the output file size. When exporting to PDF and this option is set to True, you cannot view PDF layers in the output.

(Значение по умолчанию — False)

Boolean
clip_to_elements

If set to True, the layout is clipped to the smallest bounding box that includes all layout elements.

(Значение по умолчанию — False)

Boolean
convert_markers

A Boolean that controls the conversion of character-based marker symbols to polygons. This allows the symbols to appear correctly if the symbol font is not available or cannot be embedded. However, setting this parameter to True disables font embedding for all character-based marker symbols, which can result in a change in their appearance.

(Значение по умолчанию — False)

Boolean

SVG – это формат файлов на базе XML, специально разработанный для просмотра веб-страниц. SVG могут содержать как векторную, так и растровую информацию. Для некоторых веб-браузеров может потребоваться плагин для просмотра файлов SVG. Другие веб-браузеры могут не иметь возможности для просмотра файлов SVG. Формат SVG поддерживает встроенные шрифты, поэтому даже если у пользователей не установлены шрифты Esri, символы все равно будут отображаться корректно. Вы также можете выбрать создание сжатых файлов SVG. При включении этой опции расширение файла изменяется на .svgz.

exportToTGA (out_tga, {resolution}, {color_mode}, {transparent_background}, {clip_to_elements})
ПараметрОписаниеТип данных
out_tga

A string that represents the path and file name for the output export file.

String
resolution

A number that defines the resolution of the export file in dots per inch (dpi).

(Значение по умолчанию — 96)

Integer
color_mode

This value specifies the number of bits used to describe color.

  • 8-BIT_ADAPTIVE_PALETTE8-bit adaptive palette
  • 8-BIT_GRAYSCALE8-bit grayscale
  • 24-BIT_TRUE_COLOR24-bit true color
  • 32-BIT_WITH_ALPHA32-bit with alpha

(Значение по умолчанию — 32-BIT_WITH_ALPHA)

String
transparent_background

If set to True, the white page background is set to transparent.

(Значение по умолчанию — False)

Boolean
clip_to_elements

If set to True, the layout is clipped to the smallest bounding box that includes all layout elements.

(Значение по умолчанию — False)

Boolean

Файлы TGA исторически применялись для ресурсов, которые должны использоваться в других приложениях (например, скрываемое изображение для анимированных игр), и читаются и записываются множеством популярных приложений по работе с графикой. Формат TGA поддерживает многобитную глубину, включая 32-битную с alpha-поддержкой (прозрачность).

exportToTIFF (out_tif, {resolution}, {color_mode}, {tiff_compression}, {jpeg_compression_quality}, {transparent_background}, {embed_color_profile}, {clip_to_elements}, {world_file}, {geoTIFF_tags}, {georef_mapframe})
ПараметрОписаниеТип данных
out_tif

A string that represents the path and file name of the output export file.

String
resolution

A number that defines the resolution of the export file in dots per inch (dpi).

(Значение по умолчанию — 96)

Integer
color_mode

This value specifies the number of bits used to describe color. The available options are dependent on the specified Color Model set in the layout's Color Management properties.

  • 8-BIT_ADAPTIVE_PALETTE8-bit adaptive palette. Available to RGB and CMYK.
  • 8-BIT_GRAYSCALE8-bit grayscale. Available to RGB and CMYK.
  • 24-BIT_TRUE_COLOR24-bit true color. Available only to RGB.
  • 32-BIT_WITH_ALPHA32-bit with alpha. Available only to RGB.
  • 32-BIT_CMYK_TRUE_COLOR32-bit CMYK true color. Available only to CMYK.
  • 40-BIT_CMYK_WITH_ALPHA40-bit CMYK with alpha. Available only to CMYK.

(Значение по умолчанию — 24-BIT_TRUE_COLOR)

String
tiff_compression

This value represents a compression scheme.

  • DEFLATEA lossless data compression.
  • JPEGJPEG compression.
  • LZWLempel-Ziv-Welch, a lossless data compression.
  • NONECompression is not applied.
  • PACK_BITSPack bits compression.

(Значение по умолчанию — LZW)

String
jpeg_compression_quality

This value (0–100) controls the amount of compression applied to the output image. With a JPEG image, quality is adversely affected the more compression is applied. A higher-quality (highest = 100) setting will produce sharper images and larger file sizes. A lower-quality setting will produce more image artifacts and smaller files.

(Значение по умолчанию — 80)

Integer
transparent_background

If set to True, the white page background is set to transparent.

(Значение по умолчанию — False)

Boolean
embed_color_profile

If set to True, color profile information is embedded in the image's metadata.

(Значение по умолчанию — True)

Boolean
clip_to_elements

If set to True, the layout is clipped to the smallest bounding box that includes all layout elements.

(Значение по умолчанию — False)

Boolean
world_file

If set to True and a valid georef_mapframe is set, a world file will be generated based on the map frame's coordinate system.

(Значение по умолчанию — False)

Boolean
geoTIFF_tags

If set to True and a valid georef_mapframe is set, geoTIFF tags will be embedded in the resulting image based on the map frame's coordinate system.

(Значение по умолчанию — False)

Boolean
georef_mapframe

The MapFrame used to control the coordinate system when geoTIFF_tags are set to True.

(Значение по умолчанию — None)

MapFrame

Файлы TIFF наилучшим образом подходят для импортирования в приложения для редактирования изображений и тоже считаются распространенным в ГИС растровым форматом. Но их невозможно просматривать в веб-браузерах.

getDefinition (cim_version)
ПараметрОписаниеТип данных
cim_version

A string that represents the major version of the CIM.

String

Уровень доступа CIM для дополнительных свойств объекта был введен в версии ArcGIS Pro 2.4. Если вы хотите вернуть определение CIM объекта, необходимо указать cim_version. Esri использует спецификацию семантического версионирования. Это означает, что критические изменения API разрешены в основных версиях — например, 3.0 Это даст авторам скриптов Python возможность управления версией CIM, которая будет использоваться во время запуска скрипта, если существует вероятность внесения критических изменений в новой версии. Если вы создаете скрипты для ArcGIS Pro 2.x, укажите значение cim_version как 'V2'. Если вы создаете скрипты для ArcGIS Pro 3.x, укажите значение cim_version как 'V3'. Скрипты, созданные с использованием cim_version 'V2', будут продолжать работать в ArcGIS Pro 3.x.

Более подробно о работе с CIM и примеры см. Доступ к CIM в Python.

listElements ({element_type}, {wildcard})
ПараметрОписаниеТип данных
element_type

Строка, представляющая тип элемента, который будет использоваться для фильтрации полученного списка элементов.

  • GRAPHIC_ELEMENTФильтр для объектов GraphicElement.
  • LEGEND_ELEMENTФильтр для объектов LegendElement.
  • MAPFRAME_ELEMENT Фильтр для объектов MapFrame.
  • MAPSURROUND_ELEMENTФильтр для объектов MapsurroundElement.
  • PICTURE_ELEMENTФильтр для объектов PictureElement.
  • TEXT_ELEMENTФильтр для объектов TextElement.

(Значение по умолчанию — None)

String
wildcard

Групповой символ базируется на имени элемента и не является чувствительным к регистру. Для наложения ограничения на результаты можно использовать сочетание звездочек (*) и символов.

(Значение по умолчанию — None)

String
Возвращаемое значение
Тип данныхОписание
List

Список Python объектов компоновки страницы. Могут быть получены следующие типы элементов: GraphicElement, LegendElement, MapFrame, MapsurroundElement, PictureElement и TextElement.

Каждый элемент страницы имеет свойство name, которое может быть установлено в диалоговом окне свойств элемента. Автор компоновки должен убедиться, что каждому элементу страницы присвоено уникальное имя, чтобы эти элементы можно было однозначно идентифицировать. Если два элемента имеют одинаковое имя, то нет никакого способа убедиться в том, что вы выбрали для ссылки требуемый элемент.

Метод listElements возвращает элементы внутри составного элемента в упрощенном списке. Это делает возможным легко искать и заменять, например, текстовые строки, без необходимости переходить по элементам внутри структуры составного элемента.

Параметр element_type может быть пропущен посредством передачи пустой строки или посредством включения имени параметра для всех параметров, которые следуют за пропущенным параметром. Например:


elm = lyt.listElements("", "Title")[0]

#or

elm = lyt.listElements(wildcard="Title")[0]

openView ()

Это полезно, если вид компоновки еще не открыт или в приложении активен другой вид. Этот метод создает вид компоновки, увеличенный до полного размера, и активирует его. Чтобы закрыть другие существующие виды перед открытием нового вида, используйте метод ArcGISProject closeViews.

Примечание:

Этот метод предназначен для запуска в приложении с помощью инструмента-скрипта, блокнота или окна Python. Это не будет иметь никакого эффекта, если запустить его вне приложения.

setDefinition (definition_object)
ПараметрОписаниеТип данных
definition_object

Объект измененного определения CIM, изначально полученный с помощью getDefinition.

Object

Более подробно о работе с CIM и примеры см. Доступ к CIM в Python.

Пример кода

Layout, пример 1

Следующий скрипт выполняет итерацию по всем компоновкам в текущем проекте и выводит основную информацию о каждой, включая название, размер страницы и единицы измерения, количество фреймов карты, названия фреймов карты и общее количество элементов компоновки.

aprx = arcpy.mp.ArcGISProject('CURRENT')
print(f'Total Project Layout Count: {str(len(aprx.listLayouts()))} \n')
for lyt in aprx.listLayouts():
    print(f'Layout Name: {lyt.name}')
    print(f'    Width x height: {lyt.pageWidth} x {lyt.pageHeight} units are {lyt.pageUnits}')
    print(f'    MapFrame count: {str(len(lyt.listElements("MapFrame_Element")))}')
    for mf in lyt.listElements("MapFrame_Element"):
        if len(lyt.listElements("MapFrame_Element")) > 0:
            print(f'        MapFrame name: {mf.name}')
    print(f'    Total element count: {str(len(lyt.listElements()))} \n')
Layout, пример 2

Следующий скрипт выполняет итерацию по списку названий компоновок и экспортирует каждую компоновку в PDF два раза. При первом экспорте используются настройки exportToPDF по умолчанию. При втором экспорте получается выходной файл меньшего размера, поскольку параметры resolution, image_quality и output_as_image заданы соответствующим образом.

import arcpy, os
prjPath = r'C:\Projects\YosemiteNP'
p = arcpy.mp.ArcGISProject(os.path.join(prjPath, 'Yosemite.aprx'))

layoutNames = ['Main Attractions', 'Scenic Views']
for name in layoutNames:
    lyt = p.listLayouts(name)[0]
    #export to PDF - default settings
    lyt.exportToPDF(os.path.join(prjPath, 'Output', name + '_defaults.pdf'))
    #export to PDF - smaller file size
    lyt.exportToPDF(os.path.join(prjPath, 'Output', name + '_small.pdf'), 100, 
                    image_quality = 3,
                    output_as_image = True)
Layout, пример 3

Следующий скрипт создает карту и компоновку. Он также создает в компоновке фрейм карты, стрелку севера и масштабную линейку. Вспомогательная функция rectangle включена для создания геометрии, необходимой для рамки карты и масштабной линейки. Наконец, он гарантирует, что новая компоновка будет открыта и активирована в приложении.

def MakeRec_LL(llx, lly, w, h):
    xyRecList = [[llx, lly], [llx, lly+h], [llx+w,lly+h], [llx+w,lly], [llx,lly]]
    array = arcpy.Array([arcpy.Point(*coords) for coords in xyRecList])
    rec = arcpy.Polygon(array)
    return rec

p = arcpy.mp.ArcGISProject('current')

#Create a new map and layout
m = p.createMap('New Map', 'MAP')
lyt = p.createLayout(8.5, 11, 'INCH')

#Create a map frame
mf = lyt.createMapFrame(MakeRec_LL(0.5,5.5,7.5,5), m, "New Map Frame")

#Create a north arrow
naStyle = p.listStyleItems('ArcGIS 2D', 'North_Arrow', 'Compass North 1')[0]
na = lyt.createMapSurroundElement(arcpy.Point(7,7), 'North_Arrow', mf,
                                      naStyle, "Compass North Arrow")
na.elementWidth = 0.5  

#Create a scale bar
sbName = 'Double Alternating Scale Bar 1 Metric'
sbStyle = p.listStyleItems('ArcGIS 2D', 'Scale_bar', sbName)[0]
sbEnv = MakeRec_LL(0.5, 5.5, 2.5, 0.5)
sb = lyt.createMapSurroundElement(sbEnv, 'Scale_bar', mf, sbStyle, 'New Scale Bar')

#Close all view and open and active the layout view
p.closeViews()
lyt.openView()
Layout, пример 4

В следующем скрипте показаны различные способы использования deleteElement. Имейте в виду, что для удаления элементов группы, которые могут существовать внутри других элементов группы, вы должны удалить элементы группы в обратном порядке, потому что необходимо удалить дочерние группы перед удалением родительской группы.

p = arcpy.mp.ArcGISProject('current')
lyt = p.listLayouts('Layout')[0]

#Delete one element by name
elm = lyt.listElement('GRAPHIC_ELEMENT', 'Point')[0]
lyt.deleteElement(elm)

#Delete all the group elements and their children in reverse order
for elm in reversed(lyt.listElements('GROUP_ELEMENT')):
    lyt.deleteElement(elm)

#Delete remaining elements
for elm in lyt.listElements():
    lyt.deleteElement(elm)
Layout, пример 5

В следующем скрипте показано, как использовать Python CIM Access для добавления направляющих в компоновку. Он добавляет четыре новые направляющие на расстоянии 0,5 дюйма от границ компоновки.

#CAUTION - this script will remove any existing guides

p = arcpy.mp.ArcGISProject('CURRENT')

for lyt in p.listLayouts(): 
    lyt_cim = lyt.getDefinition('V3')

    newGuides = []

    #Bottom horizontal guide
    botHorz = arcpy.cim.CreateCIMObjectFromClassName('CIMGuide', 'V3')
    botHorz.position = 0.5
    botHorz.orientation = 'Horizontal'
    newGuides.append(botHorz)

    #Top horizontal guide
    topHorz = arcpy.cim.CreateCIMObjectFromClassName('CIMGuide', 'V3')
    topHorz.position = lyt.pageHeight - 0.5
    topHorz.orientation = 'Horizontal'
    newGuides.append(topHorz)

    #Left vertical guide
    leftVert = arcpy.cim.CreateCIMObjectFromClassName('CIMGuide', 'V3')
    leftVert.position = 0.5
    leftVert.orientation = 'Vertical'
    newGuides.append(leftVert)

    #Right vertical guide
    rightVert = arcpy.cim.CreateCIMObjectFromClassName('CIMGuide', 'V3')
    rightVert.position = lyt.pageWidth - 0.5
    rightVert.orientation = 'Vertical'
    newGuides.append(rightVert)

    #Add guides and make sure they are turned on
    lyt_cim.page.guides = newGuides
    lyt_cim.page.showGuides = True

    #Set back to layer
    lyt.setDefinition(lyt_cim)