Skip to main content

changePageSize

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

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

Обсуждение

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

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

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

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

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

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

Примечание:

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

Синтаксис

changePageSize()

Свойства

Имя Объяснение Тип данных

colorModel

(Чтение / Запись)

Возвращает цветовую модель, назначенную объекту Layout. Допустимы значения CMYK или RGB.

String

mapSeries

(Только для чтения)

Возвращает объект MapSeries или объект BookmarkMapSeries, если серия карт существует и включена, в противном случае возвращает 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

Методы

changePageSize(page_width, page_height, {resize_elements})

Метод changePageSize изменяет размер компоновки.

Имя Объяснение Тип данных

page_width

A double that indicates the width of a layout and is based on the page_units value.

Double

page_height

A double that indicates the height of a layout and is based on the page_units value.

Double

resize_elements

(Дополнительный)

Specifies whether the elements will be resized. If set to True, the elements on the layout will be resized proportionally. If set to False, only the page size will change, the elements will remain their original size.

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

Boolean

createBookmarkMapSeries(mapframe, {bookmarks[bookmarks,...]})

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

Имя Объяснение Тип данных

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.

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

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

Имя Объяснение Тип данных

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.

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

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

Имя Объяснение Тип данных

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

  • DUAL_SCALE_BAR—A dual scale bar element will be created.

  • GRID—A grid or graticule will be created.

  • LEGEND—A legend element will be created.

  • NORTH_ARROW—A north arrow element will be created.

  • SCALE_BAR—A 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.

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

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

Имя Объяснение Тип данных

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.

createTableFrameElement(geometry, {mapframe}, {table[table,...]}, {fields}, {style_item}, {name})

Метод createTableFrameElement создает объект TableFrameElement в компоновке.

Имя Объяснение Тип данных

geometry

A Point or a rectangular Polygon object using layout page units.

Object

mapframe

(Дополнительный)

The MapFrame element that will be associated with the table frame element. If the default value of None is used, it can be changed at a later time using the mapframe property on the TableFrameElement class.

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

MapFrame

table[table,...]

(Дополнительный)

The Layer or Table object associated with the table frame element. If the default value of None is used, it can be changed at a later time using the table property on the TableFrameElement class.

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

Object

fields

(Дополнительный)

A list of strings that represent the table field names to display in the table frame. If the default value of None is used, it can be changed at a later time using the fields property on the TableFrameElement class.

String

style_item

(Дополнительный)

An optional reference to a StyleItem value. When using the listStyleItems method on the ArcGISProject class, you must use the TABLE_FRAME keyword for the style_class 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 table frame element. If no name is provided, the default name value will follow the automatic sequencing nomenclature, for example, Table Frame, Table Frame 1, Table Frame 2, and so on.

String

Возвращаемое значение

Тип данных Объяснение

Object

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

deleteElement(element)

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

Имя Объяснение Тип данных

element

An object that represents a layout element to be deleted.

Object

export(export_format, {display_options})

Метод export экспортирует Layout, используя указанный export_format.

Имя Объяснение Тип данных

export_format

The supported export format objects are: AIXFormat, BMPFormat, EMFFormat, EPSFormat, GIFFormat, JPEGFormat, PDFFormat, PNGFormat, SVGFormat, TGAFormat and TIFFFormat.

Object

display_options

(Дополнительный)

The DisplayOptions object includes antialiasing mode options.

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})

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

Прежние версии:

Этот метод заменен на export в версии 3.4 ArcGIS Pro и остается для использования только в устаревших скриптах. Все усовершенствования и будущие разработки будут осуществляться только методом экспорта.

Имя Объяснение Тип данных

out_aix

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

String

resolution

(Дополнительный)

Число, определяющее разрешение файла для экспорта в точках на дюйм (dpi).

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

Integer

image_quality

(Дополнительный)

Строка, определяющая качество выходного изображения, разрешение вывода слоев карты в растровом формате.

  • BEST—An output image quality resample ratio of 1

  • BETTER—An output image quality resample ratio of 2

  • NORMAL—An output image quality resample ratio of 3

  • FASTER—An output image quality resample ratio of 4

  • FASTEST—An output image quality resample ratio of 5

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

String

compress_vector_graphics

(Дополнительный)

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

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

Boolean

image_compression

(Дополнительный)

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

  • ADAPTIVE—Automatically 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.

  • DEFLATE—A lossless data compression.

  • JPEG—A lossy data compression.

  • JPEG2000—Offers higher quality compression with smaller file size than JPEG. This compression is lossless if jpeg_compression_quality is set to 100.

  • LZW—Lempel-Ziv-Welch, a lossless data compression.

  • NONE—Compression is not applied.

  • RLE—Run-length encoded compression.

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

String

jpeg_compression_quality

(Дополнительный)

Число, управляющее значением качества сжатия, если image_compression задано как ADAPTIVE или JPEG. Допустимым является диапазон от 1 до 100. Значение jpeg_compression_quality, равное 100, обеспечивает высокое качество изображений, но создает большие файлы экспорта. Рекомендуемый диапазон находится между 70 и 90.

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

Integer

embed_fonts

(Дополнительный)

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

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

Boolean

embed_color_profile

(Дополнительный)

Если задано значение True, информация о цвете профиля будет встроена в метаданные изображения.

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

Boolean

clip_to_elements

(Дополнительный)

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

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

Boolean

keep_layout_background

(Дополнительный)

При установке на True, белый фон компоновки сохраняется.

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

Boolean

convert_markers

(Дополнительный)

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

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

Boolean

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

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

Прежние версии:

Этот метод заменен на export в версии 3.4 ArcGIS Pro и остается для использования только в устаревших скриптах. Все усовершенствования и будущие разработки будут осуществляться только методом экспорта.

Имя Объяснение Тип данных

out_bmp

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

String

resolution

(Дополнительный)

Число, определяющее разрешение файла для экспорта в точках на дюйм (dpi).

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

Integer

bmp_color_mode

(Дополнительный)

Это значение определяет количество битов, используемых для описания цвета.

  • 8-BIT_ADAPTIVE_PALETTE—8-bit adaptive palette

  • 8-BIT_GRAYSCALE—8-bit grayscale

  • 24-BIT_TRUE_COLOR—24-bit true color

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

String

bmp_image_compression

(Дополнительный)

Строка, которая определяет схему сжатия, используемую для сжатия изображения или растровых данных в выходном файле. Данная опция применяется только к 8-разрядным опциям bmp_color_mode.

  • NONE—Compression is not applied.

  • RLE—Run-length encoded compression.

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

String

embed_color_profile

(Дополнительный)

Если задано значение True, информация о цвете профиля будет встроена в метаданные изображения.

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

Boolean

clip_to_elements

(Дополнительный)

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

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

Boolean

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

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

Прежние версии:

Этот метод заменен на export в версии 3.4 ArcGIS Pro и остается для использования только в устаревших скриптах. Все усовершенствования и будущие разработки будут осуществляться только методом экспорта.

Имя Объяснение Тип данных

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.

  • BEST—An output image quality resample ratio of 1

  • BETTER—An output image quality resample ratio of 2

  • NORMAL—An output image quality resample ratio of 3

  • FASTER—An output image quality resample ratio of 4

  • FASTEST—An 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

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

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

Прежние версии:

Этот метод заменен на export в версии 3.4 ArcGIS Pro и остается для использования только в устаревших скриптах. Все усовершенствования и будущие разработки будут осуществляться только методом экспорта.

Имя Объяснение Тип данных

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.

  • DEFLATE—A lossless data compression.

  • LZW—Lempel-Ziv-Welch, a lossless data compression.

  • NONE—Compression is not applied.

  • RLE—Run-length encoded compression.

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

String

image_quality

(Дополнительный)

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

  • BEST—An output image quality resample ratio of 1.

  • BETTER—An output image quality resample ratio of 2.

  • NORMAL—An output image quality resample ratio of 3.

  • FASTER—An output image quality resample ratio of 4.

  • FASTEST—An 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

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

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

Прежние версии:

Этот метод заменен на export в версии 3.4 ArcGIS Pro и остается для использования только в устаревших скриптах. Все усовершенствования и будущие разработки будут осуществляться только методом экспорта.

Имя Объяснение Тип данных

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_PALETTE—8-bit adaptive palette

  • 8-BIT_GRAYSCALE—8-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

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

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

Прежние версии:

Этот метод заменен на export в версии 3.4 ArcGIS Pro и остается для использования только в устаревших скриптах. Все усовершенствования и будущие разработки будут осуществляться только методом экспорта.

Имя Объяснение Тип данных

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_GRAYSCALE—8-bit grayscale

  • 24-BIT_TRUE_COLOR—24-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

exportToPAGX(out_pagx)

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

Имя Объяснение Тип данных

out_pagx

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

String

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).

Прежние версии:

Этот метод заменен на export в версии 3.4 ArcGIS Pro и остается для использования только в устаревших скриптах. Все усовершенствования и будущие разработки будут осуществляться только методом экспорта.

Имя Объяснение Тип данных

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.

  • BEST—An output image quality resample ratio of 1

  • BETTER—An output image quality resample ratio of 2

  • NORMAL—An output image quality resample ratio of 3

  • FASTER—An output image quality resample ratio of 4

  • FASTEST—An 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.

  • ADAPTIVE—Automatically 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.

  • DEFLATE—A lossless data compression.

  • JPEG—A lossy data compression.

  • JPEG2000—Offers higher quality compression with smaller file size than JPEG. This compression is lossless if jpeg_compression_quality is set to 100.

  • LZW—Lempel-Ziv-Welch, a lossless data compression.

  • NONE—Compression is not applied.

  • RLE—Run-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_ONLY—Export PDF layers only

  • LAYERS_AND_ATTRIBUTES—Export PDF layers and feature attributes

  • NONE—None

(Значение по умолчанию — 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

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

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

Прежние версии:

Этот метод заменен на export в версии 3.4 ArcGIS Pro и остается для использования только в устаревших скриптах. Все усовершенствования и будущие разработки будут осуществляться только методом экспорта.

Имя Объяснение Тип данных

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_PALETTE—8-bit adaptive palette

  • 8-BIT_GRAYSCALE—8-bit grayscale

  • 24-BIT_TRUE_COLOR—24-bit true color

  • 32-BIT_WITH_ALPHA—32-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

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

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

Прежние версии:

Этот метод заменен на export в версии 3.4 ArcGIS Pro и остается для использования только в устаревших скриптах. Все усовершенствования и будущие разработки будут осуществляться только методом экспорта.

Имя Объяснение Тип данных

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.

  • BEST—An output image quality resample ratio of 1.

  • BETTER—An output image quality resample ratio of 2.

  • NORMAL—An output image quality resample ratio of 3.

  • FASTER—An output image quality resample ratio of 4.

  • FASTEST—An 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

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

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

Прежние версии:

Этот метод заменен на export в версии 3.4 ArcGIS Pro и остается для использования только в устаревших скриптах. Все усовершенствования и будущие разработки будут осуществляться только методом экспорта.

Имя Объяснение Тип данных

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_PALETTE—8-bit adaptive palette

  • 8-BIT_GRAYSCALE—8-bit grayscale

  • 24-BIT_TRUE_COLOR—24-bit true color

  • 32-BIT_WITH_ALPHA—32-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

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).

Прежние версии:

Этот метод заменен на export в версии 3.4 ArcGIS Pro и остается для использования только в устаревших скриптах. Все усовершенствования и будущие разработки будут осуществляться только методом экспорта.

Имя Объяснение Тип данных

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_PALETTE—8-bit adaptive palette. Available to RGB and CMYK.

  • 8-BIT_GRAYSCALE—8-bit grayscale. Available to RGB and CMYK.

  • 24-BIT_TRUE_COLOR—24-bit true color. Available only to RGB.

  • 32-BIT_WITH_ALPHA—32-bit with alpha. Available only to RGB.

  • 32-BIT_CMYK_TRUE_COLOR—32-bit CMYK true color. Available only to CMYK.

  • 40-BIT_CMYK_WITH_ALPHA—40-bit CMYK with alpha. Available only to CMYK.

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

String

tiff_compression

(Дополнительный)

This value represents a compression scheme.

  • DEFLATE—A lossless data compression.

  • JPEG—JPEG compression.

  • LZW—Lempel-Ziv-Welch, a lossless data compression.

  • NONE—Compression is not applied.

  • PACK_BITS—Pack 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

getDefinition(cim_version)

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

Имя Объяснение Тип данных

cim_version

A string that represents the major version of the CIM.

String

Возвращаемое значение

Тип данных Объяснение

Object

Возвращает определение CIM для объекта Layout.

listElements({element_type}, {wildcard})

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

Имя Объяснение Тип данных

element_type

(Дополнительный)

A string that represents the element type that will be used to filter the returned list of elements.

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

String

wildcard

(Дополнительный)

A wildcard is based on the element name and is not case sensitive. A combination of asterisks (*) and characters can be used to help limit the results.

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

String

Возвращаемое значение

Тип данных Объяснение

List

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

openView()

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

setColorModel(color_model)

Строковая константа для установки цветовой модели, связанной с Компоновкой.

Имя Объяснение Тип данных

color_model

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

  • CMYK— Cyan, Magenta, Yellow, Black

  • RGB— Red, Green, Blue

String

setDefinition(definition_object)

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

Имя Объяснение Тип данных

definition_object

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

Object

Пример кода

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 два раза. При первом export используются настройки по умолчанию PDFFormat. При втором export получается выходной файл меньшего размера, поскольку свойства resolution, image_quality и output_as_image объекта PDFFormat устанавливаются соответствующим образом.

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

layoutNames = ['Main Attractions', 'Scenic Views']
for lytName in layoutNames:
    lyt = p.listLayouts(lytName)[0]

    #export to PDF - default settings
    pdf = arcpy.mp.CreateExportFormat('PDF', os.path.join(prjPath, 'Output', f'{lytName}_defaults.pdf'))
    lyt.export(pdf)

    #export to PDF - smaller file size
    pdf.filePath = os.path.join(prjPath, 'Output', f'{lytName}_small.pdf')
    pdf.setImageQuality("FASTEST")
    pdf.outputAsImage = True
    pdf.resolution = 72
    lyt.export(pdf)
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.listElements('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)