PowerPoint.Shape class

Representa una sola forma de la diapositiva.

Extends

Comentarios

Conjunto de API: PowerPointApi 1.3

Usada por

Ejemplos

// 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: PowerPoint.ShapeCollection = 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();
});

Propiedades

adjustments

Devuelve un Adjustments objeto que contiene valores de ajuste de todos los ajustes de esta forma.

altTextDescription

La descripción de texto alternativo de la forma.

El texto alternativo proporciona representaciones alternativas basadas en texto de la información contenida en la forma. Esta información es útil para personas con discapacidades visuales o cognitivas que no pueden ver o comprender la forma.

altTextTitle

El título del texto alternativo de la forma.

El texto alternativo proporciona representaciones alternativas basadas en texto de la información contenida en la forma. Esta información es útil para personas con discapacidades visuales o cognitivas que no pueden ver o comprender la forma. Un título se puede leer a una persona con una discapacidad y se usa para determinar si desea escuchar la descripción del contenido.

context

El contexto de solicitud asociado al objeto. De esta forma, se conecta el proceso del complemento con el proceso de la aplicación host de Office.

creationId

Obtiene el id. de creación de la forma. Devuelve null si la forma no tiene ningún Id. de creación.

customXmlParts

Devuelve una colección de elementos XML personalizados de la forma.

fill

Devuelve el formato de relleno de esta forma.

group

Devuelve lo ShapeGroup asociado a la forma. Si el tipo de forma no groupes , este método devuelve el GeneralException error.

height

Especifica la altura, en puntos, de la forma. Lanza una InvalidArgument excepción cuando se establece con un valor negativo.

id

Obtiene el identificador único de la forma.

isDecorative

Representa si la forma es decorativa o no.

Los objetos decorativos agregan interés visual, pero no son informativos (por ejemplo, bordes de estilo). People usan lectores de pantalla escucharán que se trata de objetos decorativos y sabrán que no se están perdiendo información importante.

left

Distancia, en puntos, desde el lado izquierdo de la forma al lado izquierdo de la diapositiva.

level

Devuelve el nivel de la forma especificada.

  • Un nivel de 0 significa que la forma no forma parte de un grupo.

  • Un nivel de 1 significa que la forma forma parte de un grupo de nivel superior.

  • Un nivel mayor que 1 indica que la forma es un grupo anidado.

lineFormat

Devuelve el formato de línea de esta forma.

name

Especifica el nombre de esta forma.

parentGroup

Devuelve el grupo primario de esta forma. Si la forma no forma parte de un grupo, este método devuelve el GeneralException error.

placeholderFormat

Devuelve las propiedades que se aplican específicamente a este marcador de posición. Si el tipo de forma no placeholderes , este método devuelve el GeneralException error.

rotation

Especifica el giro, en grados, de la forma alrededor del eje z. Un valor positivo indica la rotación en el sentido de las agujas del reloj y un valor negativo indica la rotación en sentido contrario a las agujas del reloj.

tags

Devuelve una colección de etiquetas en la forma.

textFrame

Devuelve el objeto PowerPoint.TextFrame de este Shapearchivo . Lanza una InvalidArgument excepción si la forma no admite un TextFramearchivo .

top

Distancia, en puntos, desde el borde superior de la forma hasta el borde superior de la diapositiva.

type

Devuelve el tipo de esta forma. Vea PowerPoint.ShapeType para obtener más información.

visible

Especifica si la forma está visible.

width

Especifica el ancho, en puntos, de la forma. Lanza una InvalidArgument excepción cuando se establece con un valor negativo.

zOrderPosition

Devuelve la posición de orden z de la forma, donde 0 representa la parte inferior de la pila de pedidos. Cada forma de una diapositiva tiene un orden Z único, pero cada diapositiva también tiene una pila de orden Z única, por lo que dos formas de diapositivas independientes podrían tener el mismo número de orden Z.

Métodos

delete()

Elimina la forma de la colección de formas. No hace nada si la forma no existe.

getGraphicOrNullObject()

Devuelve un objeto PowerPoint.Graphic si esta forma es un ShapeType.graphic. Si esta forma no es un Graphic, se devuelve un objeto con una isNullObject propiedad establecida en true . Para obtener más información, vea los métodos y propiedades *OrNullObject.

getImageAsBase64(options)

Representa una imagen de la forma.

getParentSlide()

Devuelve el objeto primario PowerPoint.Slide que contiene este Shapearchivo . Lanza una excepción si esta forma no pertenece a un Slidearchivo .

getParentSlideLayout()

Devuelve el objeto PowerPoint.SlideLayout primario que contiene este Shapearchivo . Lanza una excepción si esta forma no pertenece a un SlideLayoutarchivo .

getParentSlideLayoutOrNullObject()

Devuelve el objeto PowerPoint.SlideLayout primario que contiene este Shapearchivo . Si esta forma no pertenece a , SlideLayoutse devuelve un objeto con una isNullObject propiedad establecida en true . Para obtener más información, vea los métodos y propiedades *OrNullObject.

getParentSlideMaster()

Devuelve el objeto primario PowerPoint.SlideMaster que contiene este Shapeobjeto . Lanza una excepción si esta forma no pertenece a un SlideMasterarchivo .

getParentSlideMasterOrNullObject()

Devuelve el objeto primario PowerPoint.SlideMaster que contiene este Shapeobjeto . Si esta forma no pertenece a , SlideMasterse devuelve un objeto con una isNullObject propiedad establecida en true . Para obtener más información, vea los métodos y propiedades *OrNullObject.

getParentSlideOrNullObject()

Devuelve el objeto primario PowerPoint.Slide que contiene este Shapearchivo . Si esta forma no pertenece a , Slidese devuelve un objeto con una isNullObject propiedad establecida en true . Para obtener más información, vea los métodos y propiedades *OrNullObject.

getTable()

Devuelve el Table objeto si esta forma es una tabla.

getTextFrameOrNullObject()

Devuelve el objeto PowerPoint.TextFrame de este Shapearchivo . Si la forma no admite un TextFrame, se devuelve un objeto con una isNullObject propiedad establecida en true . Para obtener más información, vea los métodos y propiedades *OrNullObject.

load(options)

Pone en cola un comando para cargar las propiedades especificadas del objeto. Debe llamar a context.sync() antes de leer las propiedades.

load(propertyNames)

Pone en cola un comando para cargar las propiedades especificadas del objeto. Debe llamar a context.sync() antes de leer las propiedades.

load(propertyNamesAndPaths)

Pone en cola un comando para cargar las propiedades especificadas del objeto. Debe llamar a context.sync() antes de leer las propiedades.

setHyperlink(options)

Establece un hipervínculo en esto Shape con las opciones especificadas. Esto eliminará cualquier hipervínculo existente en este Shapearchivo .

setZOrder(position)

Mueve la forma especificada hacia arriba o hacia abajo en el orden z de la colección, que se desplaza delante o detrás de otras formas.

setZOrder(position)

Mueve la forma especificada hacia arriba o hacia abajo en el orden z de la colección, que se desplaza delante o detrás de otras formas.

toJSON()

Reemplaza el método JavaScript toJSON() para proporcionar una salida más útil cuando se pasa un objeto API a JSON.stringify(). (JSON.stringify, a su vez, llama al toJSON método del objeto que se le pasa). Mientras que el objeto original PowerPoint.Shape es un objeto API, el toJSON método devuelve un objeto JavaScript simple (escrito como PowerPoint.Interfaces.ShapeData) que contiene copias superficiales de cualquier propiedad secundaria cargada del objeto original.

Detalles de las propiedades

adjustments

Devuelve un Adjustments objeto que contiene valores de ajuste de todos los ajustes de esta forma.

readonly adjustments: PowerPoint.Adjustments;

Valor de propiedad

Comentarios

Conjunto de API: PowerPointApi 1.10

altTextDescription

La descripción de texto alternativo de la forma.

El texto alternativo proporciona representaciones alternativas basadas en texto de la información contenida en la forma. Esta información es útil para personas con discapacidades visuales o cognitivas que no pueden ver o comprender la forma.

altTextDescription: string;

Valor de propiedad

string

Comentarios

Conjunto de API: PowerPointApi 1.10

Ejemplos

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

// Reads the accessibility properties of the first selected shape.
await PowerPoint.run(async (context) => {
  const shapes: PowerPoint.ShapeScopedCollection = context.presentation.getSelectedShapes();
  const shapeCount = shapes.getCount();
  await context.sync();

  if (shapeCount.value === 0) {
    console.warn("No shapes are selected. Select a shape on the slide and try again.");
    return;
  }

  const shape: PowerPoint.Shape = shapes.getItemAt(0);
  shape.load("id,name,altTextTitle,altTextDescription,isDecorative");
  await context.sync();

  console.log(`Shape ID: ${shape.id}`);
  console.log(`Name: "${shape.name}"`);
  console.log(`Alt text title: "${shape.altTextTitle}"`);
  console.log(`Alt text description: "${shape.altTextDescription}"`);
  console.log(`Is decorative: ${shape.isDecorative}`);
});

altTextTitle

El título del texto alternativo de la forma.

El texto alternativo proporciona representaciones alternativas basadas en texto de la información contenida en la forma. Esta información es útil para personas con discapacidades visuales o cognitivas que no pueden ver o comprender la forma. Un título se puede leer a una persona con una discapacidad y se usa para determinar si desea escuchar la descripción del contenido.

altTextTitle: string;

Valor de propiedad

string

Comentarios

Conjunto de API: PowerPointApi 1.10

Ejemplos

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

// Insert a picture on the current slide.
await PowerPoint.run(async (context) => {
  const slide: PowerPoint.Slide = context.presentation.getSelectedSlides().getItemAt(0);

  // Use PictureAddOptions to control the position and dimensions (in points).
  const options: PowerPoint.PictureAddOptions = {
    left: 100,
    top: 100,
    width: 250,
    height: 180,
  };

  const picture: PowerPoint.Shape = slide.shapes.addPicture(getSampleImageBase64(), options);
  picture.name = "SamplePicture";

  // Set accessibility properties on the inserted picture.
  picture.altTextTitle = "Sample image";
  picture.altTextDescription = "A cartoon dog image used as a sample picture in this add-in.";

  await context.sync();
});

context

El contexto de solicitud asociado al objeto. De esta forma, se conecta el proceso del complemento con el proceso de la aplicación host de Office.

context: RequestContext;

Valor de propiedad

creationId

Obtiene el id. de creación de la forma. Devuelve null si la forma no tiene ningún Id. de creación.

readonly creationId: string | null;

Valor de propiedad

string | null

Comentarios

Conjunto de API: PowerPointApi 1.10

customXmlParts

Devuelve una colección de elementos XML personalizados de la forma.

readonly customXmlParts: PowerPoint.CustomXmlPartCollection;

Valor de propiedad

Comentarios

Conjunto de API: PowerPointApi 1.7

fill

Devuelve el formato de relleno de esta forma.

readonly fill: PowerPoint.ShapeFill;

Valor de propiedad

Comentarios

Conjunto de API: PowerPointApi 1.4

Ejemplos

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

// Changes the selected shapes fill color to red.
await PowerPoint.run(async (context) => {
  const shapes: PowerPoint.ShapeScopedCollection = context.presentation.getSelectedShapes();
  const shapeCount = shapes.getCount();
  shapes.load("items/fill/type");
  await context.sync();
  shapes.items.map((shape) => {
    const shapeFillType = shape.fill.type as PowerPoint.ShapeFillType;
    console.log(`Shape ID ${shape.id} original fill type: ${shapeFillType}`);
    shape.fill.setSolidColor("red");
  });
  await context.sync();
});

group

Devuelve lo ShapeGroup asociado a la forma. Si el tipo de forma no groupes , este método devuelve el GeneralException error.

readonly group: PowerPoint.ShapeGroup;

Valor de propiedad

Comentarios

Conjunto de API: PowerPointApi 1.8

Ejemplos

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

await PowerPoint.run(async (context) => {
  // Ungroups the first shape group on the current slide.

  // Get the shapes on the current slide.
  context.presentation.load("slides");
  const slide: PowerPoint.Slide = context.presentation.getSelectedSlides().getItemAt(0);
  slide.load("shapes/items/type,shapes/items/id");
  await context.sync();

  const shapes: PowerPoint.ShapeCollection = slide.shapes;
  const shapeGroups = shapes.items.filter((item) => item.type === PowerPoint.ShapeType.group);
  if (shapeGroups.length === 0) {
    console.warn("No shape groups on the current slide, so nothing to ungroup.");
    return;
  }

  // Ungroup the first grouped shapes.
  const firstGroupId = shapeGroups[0].id;
  const shapeGroupToUngroup = shapes.getItem(firstGroupId);
  shapeGroupToUngroup.group.ungroup();
  await context.sync();

  console.log(`Ungrouped shapes with group ID: ${firstGroupId}`);
});

height

Especifica la altura, en puntos, de la forma. Lanza una InvalidArgument excepción cuando se establece con un valor negativo.

height: number;

Valor de propiedad

number

Comentarios

Conjunto de API: PowerPointApi 1.4

Ejemplos

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

// Arranges the selected shapes in a line from left to right.
await PowerPoint.run(async (context) => {
  const shapes: PowerPoint.ShapeScopedCollection = context.presentation.getSelectedShapes();
  const shapeCount = shapes.getCount();
  shapes.load("items");
  await context.sync();
  let maxHeight = 0;
  shapes.items.map((shape) => {
    shape.load("width,height");
  });
  await context.sync();
  shapes.items.map((shape) => {
    shape.left = currentLeft;
    shape.top = currentTop;
    currentLeft += shape.width;
    if (shape.height > maxHeight) maxHeight = shape.height;
  });
  await context.sync();
  currentLeft = 0;
  if (currentTop > slideHeight - 200) currentTop = 0;
});

id

Obtiene el identificador único de la forma.

readonly id: string;

Valor de propiedad

string

Comentarios

Conjunto de API: PowerPointApi 1.3

isDecorative

Representa si la forma es decorativa o no.

Los objetos decorativos agregan interés visual, pero no son informativos (por ejemplo, bordes de estilo). People usan lectores de pantalla escucharán que se trata de objetos decorativos y sabrán que no se están perdiendo información importante.

isDecorative: boolean;

Valor de propiedad

boolean

Comentarios

Conjunto de API: PowerPointApi 1.10

Ejemplos

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

// Toggles the isDecorative property on the first selected shape.
// When isDecorative is true, screen readers announce the shape as
// decorative, indicating no alt text is needed.
await PowerPoint.run(async (context) => {
  const shapes: PowerPoint.ShapeScopedCollection = context.presentation.getSelectedShapes();
  const shapeCount = shapes.getCount();
  await context.sync();

  if (shapeCount.value === 0) {
    console.warn("No shapes are selected. Select a shape on the slide and try again.");
    return;
  }

  const shape: PowerPoint.Shape = shapes.getItemAt(0);
  shape.load("name,isDecorative");
  await context.sync();

  const wasDecorative = shape.isDecorative;
  shape.isDecorative = !wasDecorative;
  await context.sync();

  console.log(`Shape "${shape.name}" isDecorative changed: ${wasDecorative} → ${shape.isDecorative}`);
});

left

Distancia, en puntos, desde el lado izquierdo de la forma al lado izquierdo de la diapositiva.

left: number;

Valor de propiedad

number

Comentarios

Conjunto de API: PowerPointApi 1.4

Ejemplos

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

// Arranges the selected shapes in a line from left to right.
await PowerPoint.run(async (context) => {
  const shapes: PowerPoint.ShapeScopedCollection = context.presentation.getSelectedShapes();
  const shapeCount = shapes.getCount();
  shapes.load("items");
  await context.sync();
  let maxHeight = 0;
  shapes.items.map((shape) => {
    shape.load("width,height");
  });
  await context.sync();
  shapes.items.map((shape) => {
    shape.left = currentLeft;
    shape.top = currentTop;
    currentLeft += shape.width;
    if (shape.height > maxHeight) maxHeight = shape.height;
  });
  await context.sync();
  currentLeft = 0;
  if (currentTop > slideHeight - 200) currentTop = 0;
});

level

Devuelve el nivel de la forma especificada.

  • Un nivel de 0 significa que la forma no forma parte de un grupo.

  • Un nivel de 1 significa que la forma forma parte de un grupo de nivel superior.

  • Un nivel mayor que 1 indica que la forma es un grupo anidado.

readonly level: number;

Valor de propiedad

number

Comentarios

Conjunto de API: PowerPointApi 1.8

lineFormat

Devuelve el formato de línea de esta forma.

readonly lineFormat: PowerPoint.ShapeLineFormat;

Valor de propiedad

Comentarios

Conjunto de API: PowerPointApi 1.4

name

Especifica el nombre de esta forma.

name: string;

Valor de propiedad

string

Comentarios

Conjunto de API: PowerPointApi 1.4

parentGroup

Devuelve el grupo primario de esta forma. Si la forma no forma parte de un grupo, este método devuelve el GeneralException error.

readonly parentGroup: PowerPoint.Shape;

Valor de propiedad

Comentarios

Conjunto de API: PowerPointApi 1.8

placeholderFormat

Devuelve las propiedades que se aplican específicamente a este marcador de posición. Si el tipo de forma no placeholderes , este método devuelve el GeneralException error.

readonly placeholderFormat: PowerPoint.PlaceholderFormat;

Valor de propiedad

Comentarios

Conjunto de API: PowerPointApi 1.8

Ejemplos

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

// Gets the placeholder shapes in the slide.
await PowerPoint.run(async (context) => {
  // Get properties for every shape in the collection.
  const shapes: PowerPoint.ShapeCollection = context.presentation.slides.getItemAt(0).shapes;
  shapes.load("type,name");
  await context.sync();

  const placeholderShapes = [];
  console.log(`Number of shapes found: ${shapes.items.length}`);
  shapes.items.forEach((shape) => {
    if (shape.type === PowerPoint.ShapeType.placeholder) {
      // Load placeholderFormat property.
      // PowerPoint throws an exception if you try to load this property on a shape that isn't a placeholder type.
      shape.load("placeholderFormat");
      placeholderShapes.push(shape);
    }
  });
  await context.sync();

  console.log(`Number of placeholder shapes found: ${placeholderShapes.length}`);
  for (let i = 0; i < placeholderShapes.length; i++) {
    let currentPlaceholder: PowerPoint.PlaceholderFormat = placeholderShapes[i].placeholderFormat;
    let placeholderType = currentPlaceholder.type as PowerPoint.PlaceholderType;
    let placeholderContainedType = currentPlaceholder.containedType as PowerPoint.ShapeType;
    console.log(`Shape "${placeholderShapes[i].name}" placeholder properties:`);
    console.log(`\ttype: ${placeholderType}`);
    console.log(`\tcontainedType: ${placeholderContainedType}`);
  }
});

rotation

Especifica el giro, en grados, de la forma alrededor del eje z. Un valor positivo indica la rotación en el sentido de las agujas del reloj y un valor negativo indica la rotación en sentido contrario a las agujas del reloj.

rotation: number;

Valor de propiedad

number

Comentarios

Conjunto de API: PowerPointApi 1.10

tags

Devuelve una colección de etiquetas en la forma.

readonly tags: PowerPoint.TagCollection;

Valor de propiedad

Comentarios

Conjunto de API: PowerPointApi 1.3

textFrame

Devuelve el objeto PowerPoint.TextFrame de este Shapearchivo . Lanza una InvalidArgument excepción si la forma no admite un TextFramearchivo .

readonly textFrame: PowerPoint.TextFrame;

Valor de propiedad

Comentarios

Conjunto de API: PowerPointApi 1.4

top

Distancia, en puntos, desde el borde superior de la forma hasta el borde superior de la diapositiva.

top: number;

Valor de propiedad

number

Comentarios

Conjunto de API: PowerPointApi 1.4

Ejemplos

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

// Arranges the selected shapes in a line from left to right.
await PowerPoint.run(async (context) => {
  const shapes: PowerPoint.ShapeScopedCollection = context.presentation.getSelectedShapes();
  const shapeCount = shapes.getCount();
  shapes.load("items");
  await context.sync();
  let maxHeight = 0;
  shapes.items.map((shape) => {
    shape.load("width,height");
  });
  await context.sync();
  shapes.items.map((shape) => {
    shape.left = currentLeft;
    shape.top = currentTop;
    currentLeft += shape.width;
    if (shape.height > maxHeight) maxHeight = shape.height;
  });
  await context.sync();
  currentLeft = 0;
  if (currentTop > slideHeight - 200) currentTop = 0;
});

type

Devuelve el tipo de esta forma. Vea PowerPoint.ShapeType para obtener más información.

readonly type: PowerPoint.ShapeType | "Unsupported" | "Image" | "GeometricShape" | "Group" | "Line" | "Table" | "Callout" | "Chart" | "ContentApp" | "Diagram" | "Freeform" | "Graphic" | "Ink" | "Media" | "Model3D" | "Ole" | "Placeholder" | "SmartArt" | "TextBox";

Valor de propiedad

PowerPoint.ShapeType | "Unsupported" | "Image" | "GeometricShape" | "Group" | "Line" | "Table" | "Callout" | "Chart" | "ContentApp" | "Diagram" | "Freeform" | "Graphic" | "Ink" | "Media" | "Model3D" | "Ole" | "Placeholder" | "SmartArt" | "TextBox"

Comentarios

Conjunto de API: PowerPointApi 1.4

Ejemplos

// 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: PowerPoint.ShapeCollection = 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();
});

visible

Especifica si la forma está visible.

visible: boolean;

Valor de propiedad

boolean

Comentarios

Conjunto de API: PowerPointApi 1.10

width

Especifica el ancho, en puntos, de la forma. Lanza una InvalidArgument excepción cuando se establece con un valor negativo.

width: number;

Valor de propiedad

number

Comentarios

Conjunto de API: PowerPointApi 1.4

Ejemplos

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

// Arranges the selected shapes in a line from left to right.
await PowerPoint.run(async (context) => {
  const shapes: PowerPoint.ShapeScopedCollection = context.presentation.getSelectedShapes();
  const shapeCount = shapes.getCount();
  shapes.load("items");
  await context.sync();
  let maxHeight = 0;
  shapes.items.map((shape) => {
    shape.load("width,height");
  });
  await context.sync();
  shapes.items.map((shape) => {
    shape.left = currentLeft;
    shape.top = currentTop;
    currentLeft += shape.width;
    if (shape.height > maxHeight) maxHeight = shape.height;
  });
  await context.sync();
  currentLeft = 0;
  if (currentTop > slideHeight - 200) currentTop = 0;
});

zOrderPosition

Devuelve la posición de orden z de la forma, donde 0 representa la parte inferior de la pila de pedidos. Cada forma de una diapositiva tiene un orden Z único, pero cada diapositiva también tiene una pila de orden Z única, por lo que dos formas de diapositivas independientes podrían tener el mismo número de orden Z.

readonly zOrderPosition: number;

Valor de propiedad

number

Comentarios

Conjunto de API: PowerPointApi 1.8

Ejemplos

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

async function changeZOrder(operation: PowerPoint.ShapeZOrder) {
  // Changes the z-order position of the selected shapes.
  return PowerPoint.run(async (context) => {
    const selectedShapes = context.presentation.getSelectedShapes();
    selectedShapes.load();
    await context.sync();

    if (selectedShapes.items.length === 0) {
      console.log("No shapes are selected.");
    } else {
      let direction = 1; // Start with bottom-most (lowest number).

      // Start with top-most when sending to back or bringing forward.

      switch (operation) {
        case PowerPoint.ShapeZOrder.bringForward:

        case PowerPoint.ShapeZOrder.sendToBack:
          direction = -1; // Reverse direction.

          break;
      }

      // Change the z-order position for each of the selected shapes,

      // starting with the bottom-most when bringing to front or sending backward,

      // or top-most when sending to back or bringing forward,

      // so the selected shapes retain their relative z-order positions after they're changed.

      selectedShapes.items
        .sort((a, b) => (a.zOrderPosition - b.zOrderPosition) * direction)
        .forEach((shape) => {
          try {
            const originalZOrderPosition = shape.zOrderPosition;
            shape.setZOrder(operation);

            console.log(`Changed z-order of shape ${shape.id}.`);
          } catch (err) {
            console.log(`Unable to change z-order of shape ${shape.id}. ${err.message}`);
          }
        });

      await context.sync();
    }
  });
}

Detalles del método

delete()

Elimina la forma de la colección de formas. No hace nada si la forma no existe.

delete(): void;

Devoluciones

void

Comentarios

Conjunto de API: PowerPointApi 1.3

Ejemplos

// 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 then iterates through them, deleting each one.
await PowerPoint.run(async (context) => {
  const slide: PowerPoint.Slide = context.presentation.slides.getItemAt(0);
  const shapes: PowerPoint.ShapeCollection = slide.shapes;

  // Load all the shapes in the collection without loading their properties.
  shapes.load("items/$none");

  await context.sync();

  shapes.items.forEach((shape) => shape.delete());

  await context.sync();
});

getGraphicOrNullObject()

Nota

Esta API se ofrece a los desarrolladores como versión preliminar y puede cambiar en función de los comentarios que recibamos. No utilice esta API en un entorno de producción.

Devuelve un objeto PowerPoint.Graphic si esta forma es un ShapeType.graphic. Si esta forma no es un Graphic, se devuelve un objeto con una isNullObject propiedad establecida en true . Para obtener más información, vea los métodos y propiedades *OrNullObject.

getGraphicOrNullObject(): PowerPoint.Graphic;

Devoluciones

Comentarios

Conjunto de API: PowerPointApi BETA (SOLO VERSIÓN PRELIMINAR)

getImageAsBase64(options)

Representa una imagen de la forma.

getImageAsBase64(options?: PowerPoint.ShapeGetImageOptions): OfficeExtension.ClientResult<string>;

Parámetros

options
PowerPoint.ShapeGetImageOptions

Opcional. Opciones para especificar las propiedades de imagen de salida deseadas.

Devoluciones

Una cadena codificada en base64 de la imagen de forma en el formato especificado.

Comentarios

Conjunto de API: PowerPointApi 1.10

Ejemplos

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

// Gets an image of the first selected shape using default options
// (PNG format at the shape's original size).
await PowerPoint.run(async (context) => {
  const shapes: PowerPoint.ShapeScopedCollection = context.presentation.getSelectedShapes();
  const shapeCount = shapes.getCount();
  await context.sync();

  if (shapeCount.value === 0) {
    console.warn("No shapes are selected. Please select a shape and try again.");
    return;
  }

  const shape: PowerPoint.Shape = shapes.getItemAt(0);
  // Call getImageAsBase64 with no options - returns PNG at the shape's true size.
  const imageResult: OfficeExtension.ClientResult<string> = shape.getImageAsBase64();
  await context.sync();

  displayImage(imageResult.value, "Default (original size, PNG)");
});

getParentSlide()

Devuelve el objeto primario PowerPoint.Slide que contiene este Shapearchivo . Lanza una excepción si esta forma no pertenece a un Slidearchivo .

getParentSlide(): PowerPoint.Slide;

Devoluciones

Comentarios

Conjunto de API: PowerPointApi 1.5

Ejemplos

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

// Gets navigational (complex) properties of the selected text range.
await PowerPoint.run(async (context) => {
  const textRange: PowerPoint.TextRange = context.presentation.getSelectedTextRange();
  textRange.load("font,paragraphFormat/bulletFormat,paragraphFormat/horizontalAlignment");

  const parentTextFrame: PowerPoint.TextFrame = textRange.getParentTextFrame();
  const parentShape: PowerPoint.Shape = parentTextFrame.getParentShape();
  const parentSlide: PowerPoint.Slide = parentShape.getParentSlide();
  parentShape.load("id");
  parentSlide.load("id");
  await context.sync();

  console.log(`Selected text range found in parent shape with ID ${parentShape.id} on parentSlide with ID ${parentSlide.id}`);

  console.log("Font properties of selected text range:");
  console.log(`\tallCaps: ${textRange.font.allCaps}`);
  console.log(`\tbold: ${textRange.font.bold}`);
  console.log(`\tcolor: ${textRange.font.color}`);
  console.log(`\tdoubleStrikethrough: ${textRange.font.doubleStrikethrough}`);
  console.log(`\titalic: ${textRange.font.italic}`);
  console.log(`\tname: ${textRange.font.name}`);
  console.log(`\tsize: ${textRange.font.size}`);
  console.log(`\tsmallCaps: ${textRange.font.smallCaps}`);
  console.log(`\tstrikethrough: ${textRange.font.strikethrough}`);
  console.log(`\tsubscript: ${textRange.font.subscript}`);
  console.log(`\tsuperscript: ${textRange.font.superscript}`);
  console.log(`\tunderline: ${textRange.font.underline}`);

  console.log("Paragraph format properties of selected text range:");
  console.log(`\tbulletFormat.visible: ${textRange.paragraphFormat.bulletFormat.visible}`);
  console.log(`\thorizontalAlignment: ${textRange.paragraphFormat.horizontalAlignment}`);
});

getParentSlideLayout()

Devuelve el objeto PowerPoint.SlideLayout primario que contiene este Shapearchivo . Lanza una excepción si esta forma no pertenece a un SlideLayoutarchivo .

getParentSlideLayout(): PowerPoint.SlideLayout;

Devoluciones

Comentarios

Conjunto de API: PowerPointApi 1.5

getParentSlideLayoutOrNullObject()

Devuelve el objeto PowerPoint.SlideLayout primario que contiene este Shapearchivo . Si esta forma no pertenece a , SlideLayoutse devuelve un objeto con una isNullObject propiedad establecida en true . Para obtener más información, vea los métodos y propiedades *OrNullObject.

getParentSlideLayoutOrNullObject(): PowerPoint.SlideLayout;

Devoluciones

Comentarios

Conjunto de API: PowerPointApi 1.5

getParentSlideMaster()

Devuelve el objeto primario PowerPoint.SlideMaster que contiene este Shapeobjeto . Lanza una excepción si esta forma no pertenece a un SlideMasterarchivo .

getParentSlideMaster(): PowerPoint.SlideMaster;

Devoluciones

Comentarios

Conjunto de API: PowerPointApi 1.5

getParentSlideMasterOrNullObject()

Devuelve el objeto primario PowerPoint.SlideMaster que contiene este Shapeobjeto . Si esta forma no pertenece a , SlideMasterse devuelve un objeto con una isNullObject propiedad establecida en true . Para obtener más información, vea los métodos y propiedades *OrNullObject.

getParentSlideMasterOrNullObject(): PowerPoint.SlideMaster;

Devoluciones

Comentarios

Conjunto de API: PowerPointApi 1.5

getParentSlideOrNullObject()

Devuelve el objeto primario PowerPoint.Slide que contiene este Shapearchivo . Si esta forma no pertenece a , Slidese devuelve un objeto con una isNullObject propiedad establecida en true . Para obtener más información, vea los métodos y propiedades *OrNullObject.

getParentSlideOrNullObject(): PowerPoint.Slide;

Devoluciones

Comentarios

Conjunto de API: PowerPointApi 1.5

getTable()

Devuelve el Table objeto si esta forma es una tabla.

getTable(): PowerPoint.Table;

Devoluciones

Comentarios

Conjunto de API: PowerPointApi 1.8

Ejemplos

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

// Gets the table from a shape.
await PowerPoint.run(async (context) => {
  const shapes = context.presentation.getSelectedShapes();
  const shapeCount = shapes.getCount();
  shapes.load("items");
  await context.sync();

  if (shapeCount.value > 0) {
    const shape = shapes.getItemAt(0);
    shape.load("type");
    await context.sync();

    // The shape type can indicate whether the shape is a table.
    const isTable = shape.type === PowerPoint.ShapeType.table;

    if (isTable) {
      // Get the Table object for the Shape which is a table.
      const table = shape.getTable();
      table.load();
      await context.sync();

      // Get the Table row and column count.
      console.log("Table RowCount: " + table.rowCount + " and columnCount: " + table.columnCount);
    } else console.log("Selected shape isn't table.");
  } else console.log("No shape selected.");
});

getTextFrameOrNullObject()

Devuelve el objeto PowerPoint.TextFrame de este Shapearchivo . Si la forma no admite un TextFrame, se devuelve un objeto con una isNullObject propiedad establecida en true . Para obtener más información, vea los métodos y propiedades *OrNullObject.

getTextFrameOrNullObject(): PowerPoint.TextFrame;

Devoluciones

Comentarios

Conjunto de API: PowerPointApi 1.10

load(options)

Pone en cola un comando para cargar las propiedades especificadas del objeto. Debe llamar a context.sync() antes de leer las propiedades.

load(options?: PowerPoint.Interfaces.ShapeLoadOptions): PowerPoint.Shape;

Parámetros

options
PowerPoint.Interfaces.ShapeLoadOptions

Proporciona opciones para las propiedades del objeto que se van a cargar.

Devoluciones

load(propertyNames)

Pone en cola un comando para cargar las propiedades especificadas del objeto. Debe llamar a context.sync() antes de leer las propiedades.

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

Parámetros

propertyNames

string | string[]

Una cadena delimitada por comas o una matriz de cadenas que especifican las propiedades que se van a cargar.

Devoluciones

load(propertyNamesAndPaths)

Pone en cola un comando para cargar las propiedades especificadas del objeto. Debe llamar a context.sync() antes de leer las propiedades.

load(propertyNamesAndPaths?: {
            select?: string;
            expand?: string;
        }): PowerPoint.Shape;

Parámetros

propertyNamesAndPaths

{ select?: string; expand?: string; }

propertyNamesAndPaths.select es una cadena delimitada por comas que especifica las propiedades que se van a cargar y propertyNamesAndPaths.expand es una cadena delimitada por comas que especifica las propiedades de navegación que se van a cargar.

Devoluciones

Establece un hipervínculo en esto Shape con las opciones especificadas. Esto eliminará cualquier hipervínculo existente en este Shapearchivo .

setHyperlink(options?: PowerPoint.HyperlinkAddOptions): PowerPoint.Hyperlink;

Parámetros

options
PowerPoint.HyperlinkAddOptions

Opcional. Las opciones del hipervínculo.

Devoluciones

El objeto PowerPoint.Hyperlink recién creado.

Comentarios

Conjunto de API: PowerPointApi 1.10

Ejemplos

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

// Updates the hyperlink on the first selected shape on the current slide.
await PowerPoint.run(async (context) => {
  const shape: PowerPoint.Shape = context.presentation.getSelectedShapes().getItemAt(0).load("type");
  const hyperlinkAddOptions: PowerPoint.HyperlinkAddOptions = {
    address: "https://www.microsoft.com",
    screenTip: "Updated screen tip of link on shape",
  };
  const hyperlink: PowerPoint.Hyperlink = shape.setHyperlink(hyperlinkAddOptions).load("address,screenTip");
  try {
    await context.sync();
  } catch {
    console.warn("Confirm that you have at least one slide and you've selected a shape on the active slide.");
    return;
  }

  console.log(
    `Updated link on the selected ${shape.type} shape to "${hyperlink.address}" (screen tip: "${hyperlink.screenTip}").`,
  );
});

setZOrder(position)

Mueve la forma especificada hacia arriba o hacia abajo en el orden z de la colección, que se desplaza delante o detrás de otras formas.

setZOrder(position: PowerPoint.ShapeZOrder): void;

Parámetros

position
PowerPoint.ShapeZOrder

Especifica cómo mover la forma dentro de la pila de orden z. Usa la ShapeZOrder enumeración.

Devoluciones

void

Comentarios

Conjunto de API: PowerPointApi 1.8

Ejemplos

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

async function changeZOrder(operation: PowerPoint.ShapeZOrder) {
  // Changes the z-order position of the selected shapes.
  return PowerPoint.run(async (context) => {
    const selectedShapes = context.presentation.getSelectedShapes();
    selectedShapes.load();
    await context.sync();

    if (selectedShapes.items.length === 0) {
      console.log("No shapes are selected.");
    } else {
      let direction = 1; // Start with bottom-most (lowest number).

      // Start with top-most when sending to back or bringing forward.

      switch (operation) {
        case PowerPoint.ShapeZOrder.bringForward:

        case PowerPoint.ShapeZOrder.sendToBack:
          direction = -1; // Reverse direction.

          break;
      }

      // Change the z-order position for each of the selected shapes,

      // starting with the bottom-most when bringing to front or sending backward,

      // or top-most when sending to back or bringing forward,

      // so the selected shapes retain their relative z-order positions after they're changed.

      selectedShapes.items
        .sort((a, b) => (a.zOrderPosition - b.zOrderPosition) * direction)
        .forEach((shape) => {
          try {
            const originalZOrderPosition = shape.zOrderPosition;
            shape.setZOrder(operation);

            console.log(`Changed z-order of shape ${shape.id}.`);
          } catch (err) {
            console.log(`Unable to change z-order of shape ${shape.id}. ${err.message}`);
          }
        });

      await context.sync();
    }
  });
}

setZOrder(position)

Mueve la forma especificada hacia arriba o hacia abajo en el orden z de la colección, que se desplaza delante o detrás de otras formas.

setZOrder(position: "BringForward" | "BringToFront" | "SendBackward" | "SendToBack"): void;

Parámetros

position

"BringForward" | "BringToFront" | "SendBackward" | "SendToBack"

Especifica cómo mover la forma dentro de la pila de orden z. Usa la ShapeZOrder enumeración.

Devoluciones

void

Comentarios

Conjunto de API: PowerPointApi 1.8

toJSON()

Reemplaza el método JavaScript toJSON() para proporcionar una salida más útil cuando se pasa un objeto API a JSON.stringify(). (JSON.stringify, a su vez, llama al toJSON método del objeto que se le pasa). Mientras que el objeto original PowerPoint.Shape es un objeto API, el toJSON método devuelve un objeto JavaScript simple (escrito como PowerPoint.Interfaces.ShapeData) que contiene copias superficiales de cualquier propiedad secundaria cargada del objeto original.

toJSON(): PowerPoint.Interfaces.ShapeData;

Devoluciones