Поделиться через


PowerPoint.ShapeCollection class

Представляет коллекцию фигур.

Extends

Комментарии

[ Набор API: PowerPointApi 1.3 ]

Примеры

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/powerpoint/shapes/get-shapes-by-type.yaml

// Changes the transparency of every geometric shape in the slide.
await PowerPoint.run(async (context) => {
  // Get the type of shape for every shape in the collection.
  const shapes = context.presentation.slides.getItemAt(0).shapes;
  shapes.load("type");
  await context.sync();

  // Change the shape transparency to be halfway transparent.
  shapes.items.forEach((shape) => {
    if (shape.type === PowerPoint.ShapeType.geometricShape) {
      shape.fill.transparency = 0.5;
    }
  });
  await context.sync();
});

Свойства

context

Контекст запроса, связанный с объектом . Это соединяет процесс надстройки с процессом ведущего приложения Office.

items

Получает загруженные дочерние элементы в этой коллекции.

Методы

addGeometricShape(geometricShapeType, options)

Добавляет геометрическую фигуру на слайд. Shape Возвращает объект, представляющий новую фигуру.

addGeometricShape(geometricShapeTypeString, options)

Добавляет геометрическую фигуру на слайд. Shape Возвращает объект, представляющий новую фигуру.

addLine(connectorType, options)

Добавляет строку на слайд. Shape Возвращает объект , представляющий новую строку.

addLine(connectorTypeString, options)

Добавляет строку на слайд. Shape Возвращает объект , представляющий новую строку.

addTextBox(text, options)

Добавляет на слайд текстовое поле с указанным текстом в качестве содержимого. Shape Возвращает объект , представляющий новое текстовое поле.

getCount()

Возвращает количество фигур в коллекции.

getItem(key)

Получает фигуру, используя ее уникальный идентификатор. Если фигура не существует, возникает ошибка.

getItemAt(index)

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

getItemOrNullObject(id)

Получает фигуру, используя ее уникальный идентификатор. Если такая фигура не существует, возвращается объект со свойством isNullObject true.

load(options)

Добавляет в очередь команду для загрузки указанных свойств объекта. Перед чтением свойств требуется вызвать метод context.sync().

load(propertyNames)

Добавляет в очередь команду для загрузки указанных свойств объекта. Перед чтением свойств требуется вызвать метод context.sync().

load(propertyNamesAndPaths)

Добавляет в очередь команду для загрузки указанных свойств объекта. Перед чтением свойств требуется вызвать метод context.sync().

toJSON()

Переопределяет метод JavaScript toJSON() , чтобы обеспечить более полезные выходные данные при передаче объекта API в JSON.stringify(). (JSON.stringifyв свою очередь вызывает toJSON метод переданного ему объекта.) В то время как исходный PowerPoint.ShapeCollection объект является объектом API, toJSON метод возвращает обычный объект JavaScript (типизированный как PowerPoint.Interfaces.ShapeCollectionData), содержащий массив "items" с мелкими копиями всех загруженных свойств из элементов коллекции.

Сведения о свойстве

context

Контекст запроса, связанный с объектом . Это соединяет процесс надстройки с процессом ведущего приложения Office.

context: RequestContext;

Значение свойства

items

Получает загруженные дочерние элементы в этой коллекции.

readonly items: PowerPoint.Shape[];

Значение свойства

Сведения о методе

addGeometricShape(geometricShapeType, options)

Добавляет геометрическую фигуру на слайд. Shape Возвращает объект, представляющий новую фигуру.

addGeometricShape(geometricShapeType: PowerPoint.GeometricShapeType, options?: PowerPoint.ShapeAddOptions): PowerPoint.Shape;

Параметры

geometricShapeType
PowerPoint.GeometricShapeType

Задает тип геометрической фигуры. Дополнительные сведения см. в разделе PowerPoint.GeometryShapeType .

options
PowerPoint.ShapeAddOptions

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

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

Вновь вставленная фигура.

Комментарии

[ Набор API: PowerPointApi 1.4 ]

Примеры

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/powerpoint/shapes/shapes.yaml

// This function gets the collection of shapes on the first slide,
// and adds a hexagon shape to the collection, while specifying its
// location and size. Then it names the shape.
await PowerPoint.run(async (context) => {
  const shapes = context.presentation.slides.getItemAt(0).shapes;
  const hexagon = shapes.addGeometricShape(PowerPoint.GeometricShapeType.hexagon, 
      {
        left: 100,
        top: 100,
        height: 150,
        width: 150
      });
  hexagon.name = "Hexagon";

  await context.sync();
});

addGeometricShape(geometricShapeTypeString, options)

Добавляет геометрическую фигуру на слайд. Shape Возвращает объект, представляющий новую фигуру.

addGeometricShape(geometricShapeTypeString: "LineInverse" | "Triangle" | "RightTriangle" | "Rectangle" | "Diamond" | "Parallelogram" | "Trapezoid" | "NonIsoscelesTrapezoid" | "Pentagon" | "Hexagon" | "Heptagon" | "Octagon" | "Decagon" | "Dodecagon" | "Star4" | "Star5" | "Star6" | "Star7" | "Star8" | "Star10" | "Star12" | "Star16" | "Star24" | "Star32" | "RoundRectangle" | "Round1Rectangle" | "Round2SameRectangle" | "Round2DiagonalRectangle" | "SnipRoundRectangle" | "Snip1Rectangle" | "Snip2SameRectangle" | "Snip2DiagonalRectangle" | "Plaque" | "Ellipse" | "Teardrop" | "HomePlate" | "Chevron" | "PieWedge" | "Pie" | "BlockArc" | "Donut" | "NoSmoking" | "RightArrow" | "LeftArrow" | "UpArrow" | "DownArrow" | "StripedRightArrow" | "NotchedRightArrow" | "BentUpArrow" | "LeftRightArrow" | "UpDownArrow" | "LeftUpArrow" | "LeftRightUpArrow" | "QuadArrow" | "LeftArrowCallout" | "RightArrowCallout" | "UpArrowCallout" | "DownArrowCallout" | "LeftRightArrowCallout" | "UpDownArrowCallout" | "QuadArrowCallout" | "BentArrow" | "UturnArrow" | "CircularArrow" | "LeftCircularArrow" | "LeftRightCircularArrow" | "CurvedRightArrow" | "CurvedLeftArrow" | "CurvedUpArrow" | "CurvedDownArrow" | "SwooshArrow" | "Cube" | "Can" | "LightningBolt" | "Heart" | "Sun" | "Moon" | "SmileyFace" | "IrregularSeal1" | "IrregularSeal2" | "FoldedCorner" | "Bevel" | "Frame" | "HalfFrame" | "Corner" | "DiagonalStripe" | "Chord" | "Arc" | "LeftBracket" | "RightBracket" | "LeftBrace" | "RightBrace" | "BracketPair" | "BracePair" | "Callout1" | "Callout2" | "Callout3" | "AccentCallout1" | "AccentCallout2" | "AccentCallout3" | "BorderCallout1" | "BorderCallout2" | "BorderCallout3" | "AccentBorderCallout1" | "AccentBorderCallout2" | "AccentBorderCallout3" | "WedgeRectCallout" | "WedgeRRectCallout" | "WedgeEllipseCallout" | "CloudCallout" | "Cloud" | "Ribbon" | "Ribbon2" | "EllipseRibbon" | "EllipseRibbon2" | "LeftRightRibbon" | "VerticalScroll" | "HorizontalScroll" | "Wave" | "DoubleWave" | "Plus" | "FlowChartProcess" | "FlowChartDecision" | "FlowChartInputOutput" | "FlowChartPredefinedProcess" | "FlowChartInternalStorage" | "FlowChartDocument" | "FlowChartMultidocument" | "FlowChartTerminator" | "FlowChartPreparation" | "FlowChartManualInput" | "FlowChartManualOperation" | "FlowChartConnector" | "FlowChartPunchedCard" | "FlowChartPunchedTape" | "FlowChartSummingJunction" | "FlowChartOr" | "FlowChartCollate" | "FlowChartSort" | "FlowChartExtract" | "FlowChartMerge" | "FlowChartOfflineStorage" | "FlowChartOnlineStorage" | "FlowChartMagneticTape" | "FlowChartMagneticDisk" | "FlowChartMagneticDrum" | "FlowChartDisplay" | "FlowChartDelay" | "FlowChartAlternateProcess" | "FlowChartOffpageConnector" | "ActionButtonBlank" | "ActionButtonHome" | "ActionButtonHelp" | "ActionButtonInformation" | "ActionButtonForwardNext" | "ActionButtonBackPrevious" | "ActionButtonEnd" | "ActionButtonBeginning" | "ActionButtonReturn" | "ActionButtonDocument" | "ActionButtonSound" | "ActionButtonMovie" | "Gear6" | "Gear9" | "Funnel" | "MathPlus" | "MathMinus" | "MathMultiply" | "MathDivide" | "MathEqual" | "MathNotEqual" | "CornerTabs" | "SquareTabs" | "PlaqueTabs" | "ChartX" | "ChartStar" | "ChartPlus", options?: PowerPoint.ShapeAddOptions): PowerPoint.Shape;

Параметры

geometricShapeTypeString

"LineInverse" | "Triangle" | "RightTriangle" | "Rectangle" | "Diamond" | "Parallelogram" | "Trapezoid" | "NonIsoscelesTrapezoid" | "Pentagon" | "Hexagon" | "Heptagon" | "Octagon" | "Decagon" | "Dodecagon" | "Star4" | "Star5" | "Star6" | "Star7" | "Star8" | "Star10" | "Star12" | "Star16" | "Star24" | "Star32" | "RoundRectangle" | "Round1Rectangle" | "Round2SameRectangle" | "Round2DiagonalRectangle" | "SnipRoundRectangle" | "Snip1Rectangle" | "Snip2SameRectangle" | "Snip2DiagonalRectangle" | "Plaque" | "Ellipse" | "Teardrop" | "HomePlate" | "Chevron" | "PieWedge" | "Pie" | "BlockArc" | "Donut" | "NoSmoking" | "RightArrow" | "LeftArrow" | "UpArrow" | "DownArrow" | "StripedRightArrow" | "NotchedRightArrow" | "BentUpArrow" | "LeftRightArrow" | "UpDownArrow" | "LeftUpArrow" | "LeftRightUpArrow" | "QuadArrow" | "LeftArrowCallout" | "RightArrowCallout" | "UpArrowCallout" | "DownArrowCallout" | "LeftRightArrowCallout" | "UpDownArrowCallout" | "QuadArrowCallout" | "BentArrow" | "UturnArrow" | "CircularArrow" | "LeftCircularArrow" | "LeftRightCircularArrow" | "CurvedRightArrow" | "CurvedLeftArrow" | "CurvedUpArrow" | "CurvedDownArrow" | "SwooshArrow" | "Cube" | "Can" | "LightningBolt" | "Heart" | "Sun" | "Moon" | "SmileyFace" | "IrregularSeal1" | "IrregularSeal2" | "FoldedCorner" | "Bevel" | "Frame" | "HalfFrame" | "Corner" | "DiagonalStripe" | "Chord" | "Arc" | "LeftBracket" | "RightBracket" | "LeftBrace" | "RightBrace" | "BracketPair" | "BracePair" | "Callout1" | "Callout2" | "Callout3" | "AccentCallout1" | "AccentCallout2" | "AccentCallout3" | "BorderCallout1" | "BorderCallout2" | "BorderCallout3" | "AccentBorderCallout1" | "AccentBorderCallout2" | "AccentBorderCallout3" | "WedgeRectCallout" | "WedgeRRectCallout" | "WedgeEllipseCallout" | "CloudCallout" | "Cloud" | "Ribbon" | "Ribbon2" | "EllipseRibbon" | "EllipseRibbon2" | "LeftRightRibbon" | "VerticalScroll" | "HorizontalScroll" | "Wave" | "DoubleWave" | "Plus" | "FlowChartProcess" | "FlowChartDecision" | "FlowChartInputOutput" | "FlowChartPredefinedProcess" | "FlowChartInternalStorage" | "FlowChartDocument" | "FlowChartMultidocument" | "FlowChartTerminator" | "FlowChartPreparation" | "FlowChartManualInput" | "FlowChartManualOperation" | "FlowChartConnector" | "FlowChartPunchedCard" | "FlowChartPunchedTape" | "FlowChartSummingJunction" | "FlowChartOr" | "FlowChartCollate" | "FlowChartSort" | "FlowChartExtract" | "FlowChartMerge" | "FlowChartOfflineStorage" | "FlowChartOnlineStorage" | "FlowChartMagneticTape" | "FlowChartMagneticDisk" | "FlowChartMagneticDrum" | "FlowChartDisplay" | "FlowChartDelay" | "FlowChartAlternateProcess" | "FlowChartOffpageConnector" | "ActionButtonBlank" | "ActionButtonHome" | "ActionButtonHelp" | "ActionButtonInformation" | "ActionButtonForwardNext" | "ActionButtonBackPrevious" | "ActionButtonEnd" | "ActionButtonBeginning" | "ActionButtonReturn" | "ActionButtonDocument" | "ActionButtonSound" | "ActionButtonMovie" | "Gear6" | "Gear9" | "Funnel" | "MathPlus" | "MathMinus" | "MathMultiply" | "MathDivide" | "MathEqual" | "MathNotEqual" | "CornerTabs" | "SquareTabs" | "PlaqueTabs" | "ChartX" | "ChartStar" | "ChartPlus"

Задает тип геометрической фигуры. Дополнительные сведения см. в разделе PowerPoint.GeometryShapeType .

options
PowerPoint.ShapeAddOptions

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

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

Вновь вставленная фигура.

Комментарии

[ Набор API: PowerPointApi 1.4 ]

addLine(connectorType, options)

Добавляет строку на слайд. Shape Возвращает объект , представляющий новую строку.

addLine(connectorType?: PowerPoint.ConnectorType, options?: PowerPoint.ShapeAddOptions): PowerPoint.Shape;

Параметры

connectorType
PowerPoint.ConnectorType

Указывает тип соединителя строки. Если этот параметр не указан, straight будет использоваться тип соединителя. Дополнительные сведения см. в разделе PowerPoint.ConnectorType .

options
PowerPoint.ShapeAddOptions

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

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

Вновь вставленная фигура.

Комментарии

[ Набор API: PowerPointApi 1.4 ]

Примеры

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/powerpoint/shapes/shapes.yaml

// This function gets the collection of shapes on the first slide,
// and adds a line to the collection, while specifying its
// start and end points. Then it names the shape.
await PowerPoint.run(async (context) => {
  const shapes = context.presentation.slides.getItemAt(0).shapes;

  // For a line, left and top are the coordinates of the start point,
  // while height and width are the coordinates of the end point.
  const line = shapes.addLine(PowerPoint.ConnectorType.straight, 
      { 
        left: 400, 
        top: 200, 
        height: 20, 
        width: 150 
      });
  line.name = "StraightLine";

  await context.sync();
});

addLine(connectorTypeString, options)

Добавляет строку на слайд. Shape Возвращает объект , представляющий новую строку.

addLine(connectorTypeString?: "Straight" | "Elbow" | "Curve", options?: PowerPoint.ShapeAddOptions): PowerPoint.Shape;

Параметры

connectorTypeString

"Straight" | "Elbow" | "Curve"

Указывает тип соединителя строки. Если этот параметр не указан, straight будет использоваться тип соединителя. Дополнительные сведения см. в разделе PowerPoint.ConnectorType .

options
PowerPoint.ShapeAddOptions

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

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

Вновь вставленная фигура.

Комментарии

[ Набор API: PowerPointApi 1.4 ]

addTextBox(text, options)

Добавляет на слайд текстовое поле с указанным текстом в качестве содержимого. Shape Возвращает объект , представляющий новое текстовое поле.

addTextBox(text: string, options?: PowerPoint.ShapeAddOptions): PowerPoint.Shape;

Параметры

text

string

Указывает текст, который будет отображаться в созданном текстовом поле.

options
PowerPoint.ShapeAddOptions

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

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

Вновь вставленная фигура.

Комментарии

[ Набор API: PowerPointApi 1.4 ]

Примеры

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/powerpoint/shapes/shapes.yaml

// This function gets the collection of shapes on the first slide,
// and adds a text box to the collection, while specifying its text,
// location, and size. Then it names the text box.
await PowerPoint.run(async (context) => {
  const shapes = context.presentation.slides.getItemAt(0).shapes;
  const textbox = shapes.addTextBox("Hello!", 
      { 
        left: 100, 
        top: 300, 
        height: 300, 
        width: 450 
      });
  textbox.name = "Textbox";

  return context.sync();
});

getCount()

Возвращает количество фигур в коллекции.

getCount(): OfficeExtension.ClientResult<number>;

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

Количество фигур в коллекции.

Комментарии

[ Набор API: PowerPointApi 1.3 ]

getItem(key)

Получает фигуру, используя ее уникальный идентификатор. Если фигура не существует, возникает ошибка.

getItem(key: string): PowerPoint.Shape;

Параметры

key

string

Идентификатор фигуры.

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

Фигура с уникальным идентификатором. Если такая фигура не существует, возникает ошибка.

Комментарии

[ Набор API: PowerPointApi 1.3 ]

getItemAt(index)

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

getItemAt(index: number): PowerPoint.Shape;

Параметры

index

number

Индекс фигуры в коллекции.

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

Фигура по заданному индексу. Если индекс выходит за пределы диапазона, возникает ошибка.

Комментарии

[ Набор API: PowerPointApi 1.3 ]

Примеры

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/powerpoint/tags/tags.yaml

await PowerPoint.run(async function(context) {
  const slide = context.presentation.slides.getItemAt(0);
  const shape = slide.shapes.getItemAt(0);
  shape.tags.add("MOUNTAIN", "Denali");

  await context.sync();

  const myShapeTag = shape.tags.getItem("MOUNTAIN");
  myShapeTag.load("key, value");

  await context.sync();

  console.log("Added key " + JSON.stringify(myShapeTag.key) + " with value " + JSON.stringify(myShapeTag.value));
});

getItemOrNullObject(id)

Получает фигуру, используя ее уникальный идентификатор. Если такая фигура не существует, возвращается объект со свойством isNullObject true.

getItemOrNullObject(id: string): PowerPoint.Shape;

Параметры

id

string

Идентификатор фигуры.

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

Фигура с уникальным идентификатором. Если такая фигура не существует, возвращается объект со свойством isNullObject true.

Комментарии

[ Набор API: PowerPointApi 1.3 ]

load(options)

Добавляет в очередь команду для загрузки указанных свойств объекта. Перед чтением свойств требуется вызвать метод context.sync().

load(options?: PowerPoint.Interfaces.ShapeCollectionLoadOptions & PowerPoint.Interfaces.CollectionLoadOptions): PowerPoint.ShapeCollection;

Параметры

options

PowerPoint.Interfaces.ShapeCollectionLoadOptions & PowerPoint.Interfaces.CollectionLoadOptions

Предоставляет параметры свойств объекта для загрузки.

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

load(propertyNames)

Добавляет в очередь команду для загрузки указанных свойств объекта. Перед чтением свойств требуется вызвать метод context.sync().

load(propertyNames?: string | string[]): PowerPoint.ShapeCollection;

Параметры

propertyNames

string | string[]

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

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

Примеры

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/powerpoint/shapes/get-shapes-by-type.yaml

// Changes the transparency of every geometric shape in the slide.
await PowerPoint.run(async (context) => {
  // Get the type of shape for every shape in the collection.
  const shapes = context.presentation.slides.getItemAt(0).shapes;
  shapes.load("type");
  await context.sync();

  // Change the shape transparency to be halfway transparent.
  shapes.items.forEach((shape) => {
    if (shape.type === PowerPoint.ShapeType.geometricShape) {
      shape.fill.transparency = 0.5;
    }
  });
  await context.sync();
});

load(propertyNamesAndPaths)

Добавляет в очередь команду для загрузки указанных свойств объекта. Перед чтением свойств требуется вызвать метод context.sync().

load(propertyNamesAndPaths?: OfficeExtension.LoadOption): PowerPoint.ShapeCollection;

Параметры

propertyNamesAndPaths
OfficeExtension.LoadOption

propertyNamesAndPaths.select — это строка с разделителями-запятыми, указывающая загружаемые свойства, и propertyNamesAndPaths.expand строка с разделителями-запятыми, указывающая загружаемые свойства навигации.

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

toJSON()

Переопределяет метод JavaScript toJSON() , чтобы обеспечить более полезные выходные данные при передаче объекта API в JSON.stringify(). (JSON.stringifyв свою очередь вызывает toJSON метод переданного ему объекта.) В то время как исходный PowerPoint.ShapeCollection объект является объектом API, toJSON метод возвращает обычный объект JavaScript (типизированный как PowerPoint.Interfaces.ShapeCollectionData), содержащий массив "items" с мелкими копиями всех загруженных свойств из элементов коллекции.

toJSON(): PowerPoint.Interfaces.ShapeCollectionData;

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