PowerPoint.Shape class
Representa uma única forma no slide.
- Extends
Comentários
Conjunto de APIs: PowerPointApi 1.3
Usada por
- PowerPoint.Binding: getShape
- PowerPoint.BindingCollection: adicionar
- PowerPoint.Graphic: forma
- PowerPoint.Hyperlink: getLinkedShapeOrNullObject
- PowerPoint.HyperlinkCollection: adicionar
- PowerPoint.ShapeCollection: addGeometricShape, addGroup, addLine, addPicture, addTable, addTextBox, getItem, getItemAt, getItemOrNullObject, items
- PowerPoint.ShapeGroup: forma
- PowerPoint.ShapeScopedCollection: getItem, getItemAt, getItemOrNullObject, group, items
- PowerPoint.Table: getShape
- PowerPoint.TextFrame: getParentShape
Exemplos
// 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();
});
Propriedades
| adjustments | Retorna um |
| alt |
A descrição de texto alternativo da Forma. O texto Alt fornece representações alternativas baseadas em texto das informações contidas na Forma. Essas informações são úteis para pessoas com deficiência visual ou cognitiva que podem não ser capazes de ver ou entender a forma. |
| alt |
O título de texto alt da Forma. O texto Alt fornece representações alternativas baseadas em texto das informações contidas na Forma. Essas informações são úteis para pessoas com deficiência visual ou cognitiva que podem não ser capazes de ver ou entender a forma. Um título pode ser lido para uma pessoa com deficiência e é usado para determinar se ela deseja ouvir a descrição do conteúdo. |
| context | O contexto de solicitação associado ao objeto. Isso conecta o processo do suplemento ao processo do aplicativo host do Office. |
| creation |
Obtém a ID de criação da forma. Retorna |
| custom |
Retorna uma coleção de partes XML personalizadas na forma. |
| fill | Retorna a formatação de preenchimento dessa forma. |
| group | Retorna o |
| height | Especifica a altura, em pontos, da forma. Lança uma |
| id | Obtém a ID exclusiva da forma. |
| is |
Representa se a forma é decorativa ou não. Objetos decorativos adicionam interesse visual, mas não são informativos (por exemplo, bordas estilísticas). People que usam leitores de tela ouvirão que estes são decorativos, então eles sabem que não estão perdendo nenhuma informação importante. |
| left | A distância, em pontos, do lado esquerdo da forma até o lado esquerdo do slide. |
| level | Retorna o nível da forma especificada.
|
| line |
Retorna a formatação de linha do objeto de forma. |
| name | Especifica o nome dessa forma. |
| parent |
Retorna o grupo pai dessa forma. Se a forma não fizer parte de um grupo, esse método retornará o |
| placeholder |
Retorna as propriedades que se aplicam especificamente a esse espaço reservado. Se o tipo de forma não |
| rotation | Especifica a rotação, em graus, da forma em torno do eixo z. Um valor positivo indica rotação no sentido horário e um valor negativo indica rotação no sentido anti-horário. |
| tags | Retorna uma coleção de marcas na forma. |
| text |
Retorna o objeto PowerPoint.TextFrame deste |
| top | A distância, em pontos, da borda superior da forma até a borda superior do slide. |
| type | Retorna o tipo dessa forma. Confira PowerPoint.ShapeType para obter detalhes. |
| visible | Especifica se a forma é visível. |
| width | Especifica a largura, em pontos, da forma. Lança uma |
| z |
Retorna a posição de ordem z da forma, com 0 representando a parte inferior da pilha de pedidos. Todas as formas em um slide têm uma ordem z exclusiva, mas cada slide também tem uma pilha de ordem z exclusiva, portanto, duas formas em slides separados podem ter o mesmo número de ordem z. |
Métodos
| delete() | Exclui a forma da coleção de formas. Não fará nada se a forma não existir. |
| get |
Retorna um objeto PowerPoint.Graphic se essa forma é um ShapeType.graphic. Se essa forma não for um |
| get |
Renderiza uma imagem da forma. |
| get |
Retorna o objeto PowerPoint.Slide pai que contém esse |
| get |
Retorna o objeto PowerPoint.SlideLayout pai que contém esse |
| get |
Retorna o objeto PowerPoint.SlideLayout pai que contém esse |
| get |
Retorna o objeto pai PowerPoint.SlideMaster que contém esse |
| get |
Retorna o objeto pai PowerPoint.SlideMaster que contém esse |
| get |
Retorna o objeto PowerPoint.Slide pai que contém esse |
| get |
Retorna o |
| get |
Retorna o objeto PowerPoint.TextFrame deste |
| load(options) | Coloca um comando na fila para carregar as propriedades especificadas do objeto. Você deve chamar |
| load(property |
Coloca um comando na fila para carregar as propriedades especificadas do objeto. Você deve chamar |
| load(property |
Coloca um comando na fila para carregar as propriedades especificadas do objeto. Você deve chamar |
| set |
Define um hiperlink com |
| set |
Move a forma especificada para cima ou para baixo na ordem z da coleção, que a desloca para frente ou para trás de outras formas. |
| set |
Move a forma especificada para cima ou para baixo na ordem z da coleção, que a desloca para frente ou para trás de outras formas. |
| toJSON() | Substitui o método JavaScript |
Detalhes da propriedade
adjustments
Retorna um Adjustments objeto que contém valores de ajuste para todos os ajustes nessa forma.
readonly adjustments: PowerPoint.Adjustments;
Valor da propriedade
Comentários
altTextDescription
A descrição de texto alternativo da Forma.
O texto Alt fornece representações alternativas baseadas em texto das informações contidas na Forma. Essas informações são úteis para pessoas com deficiência visual ou cognitiva que podem não ser capazes de ver ou entender a forma.
altTextDescription: string;
Valor da propriedade
string
Comentários
Conjunto de APIs: PowerPointApi 1.10
Exemplos
// 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
O título de texto alt da Forma.
O texto Alt fornece representações alternativas baseadas em texto das informações contidas na Forma. Essas informações são úteis para pessoas com deficiência visual ou cognitiva que podem não ser capazes de ver ou entender a forma. Um título pode ser lido para uma pessoa com deficiência e é usado para determinar se ela deseja ouvir a descrição do conteúdo.
altTextTitle: string;
Valor da propriedade
string
Comentários
Conjunto de APIs: PowerPointApi 1.10
Exemplos
// 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
O contexto de solicitação associado ao objeto. Isso conecta o processo do suplemento ao processo do aplicativo host do Office.
context: RequestContext;
Valor da propriedade
creationId
Obtém a ID de criação da forma. Retorna null se a forma não tem ID de criação.
readonly creationId: string | null;
Valor da propriedade
string | null
Comentários
customXmlParts
Retorna uma coleção de partes XML personalizadas na forma.
readonly customXmlParts: PowerPoint.CustomXmlPartCollection;
Valor da propriedade
Comentários
fill
Retorna a formatação de preenchimento dessa forma.
readonly fill: PowerPoint.ShapeFill;
Valor da propriedade
Comentários
Conjunto de APIs: PowerPointApi 1.4
Exemplos
// 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
Retorna o ShapeGroup associado à forma. Se o tipo de forma não groupfor , esse método retornará o GeneralException erro.
readonly group: PowerPoint.ShapeGroup;
Valor da propriedade
Comentários
Conjunto de APIs: PowerPointApi 1.8
Exemplos
// 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 a altura, em pontos, da forma. Lança uma InvalidArgument exceção quando definido com um valor negativo.
height: number;
Valor da propriedade
number
Comentários
Conjunto de APIs: PowerPointApi 1.4
Exemplos
// 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
Obtém a ID exclusiva da forma.
readonly id: string;
Valor da propriedade
string
Comentários
isDecorative
Representa se a forma é decorativa ou não.
Objetos decorativos adicionam interesse visual, mas não são informativos (por exemplo, bordas estilísticas). People que usam leitores de tela ouvirão que estes são decorativos, então eles sabem que não estão perdendo nenhuma informação importante.
isDecorative: boolean;
Valor da propriedade
boolean
Comentários
Conjunto de APIs: PowerPointApi 1.10
Exemplos
// 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
A distância, em pontos, do lado esquerdo da forma até o lado esquerdo do slide.
left: number;
Valor da propriedade
number
Comentários
Conjunto de APIs: PowerPointApi 1.4
Exemplos
// 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
Retorna o nível da forma especificada.
Um nível de 0 significa que a forma não faz parte de um grupo.
Um nível de 1 significa que a forma faz parte de um grupo de nível superior.
Um nível maior que 1 indica que a forma é um grupo aninhado.
readonly level: number;
Valor da propriedade
number
Comentários
lineFormat
Retorna a formatação de linha do objeto de forma.
readonly lineFormat: PowerPoint.ShapeLineFormat;
Valor da propriedade
Comentários
name
Especifica o nome dessa forma.
name: string;
Valor da propriedade
string
Comentários
parentGroup
Retorna o grupo pai dessa forma. Se a forma não fizer parte de um grupo, esse método retornará o GeneralException erro.
readonly parentGroup: PowerPoint.Shape;
Valor da propriedade
Comentários
placeholderFormat
Retorna as propriedades que se aplicam especificamente a esse espaço reservado. Se o tipo de forma não placeholderfor , esse método retornará o GeneralException erro.
readonly placeholderFormat: PowerPoint.PlaceholderFormat;
Valor da propriedade
Comentários
Conjunto de APIs: PowerPointApi 1.8
Exemplos
// 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 a rotação, em graus, da forma em torno do eixo z. Um valor positivo indica rotação no sentido horário e um valor negativo indica rotação no sentido anti-horário.
rotation: number;
Valor da propriedade
number
Comentários
tags
Retorna uma coleção de marcas na forma.
readonly tags: PowerPoint.TagCollection;
Valor da propriedade
Comentários
textFrame
Retorna o objeto PowerPoint.TextFrame deste Shape. Lançará uma InvalidArgument exceção se a forma não for compatível com um TextFramedomínio .
readonly textFrame: PowerPoint.TextFrame;
Valor da propriedade
Comentários
top
A distância, em pontos, da borda superior da forma até a borda superior do slide.
top: number;
Valor da propriedade
number
Comentários
Conjunto de APIs: PowerPointApi 1.4
Exemplos
// 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
Retorna o tipo dessa forma. Confira PowerPoint.ShapeType para obter detalhes.
readonly type: PowerPoint.ShapeType | "Unsupported" | "Image" | "GeometricShape" | "Group" | "Line" | "Table" | "Callout" | "Chart" | "ContentApp" | "Diagram" | "Freeform" | "Graphic" | "Ink" | "Media" | "Model3D" | "Ole" | "Placeholder" | "SmartArt" | "TextBox";
Valor da propriedade
PowerPoint.ShapeType | "Unsupported" | "Image" | "GeometricShape" | "Group" | "Line" | "Table" | "Callout" | "Chart" | "ContentApp" | "Diagram" | "Freeform" | "Graphic" | "Ink" | "Media" | "Model3D" | "Ole" | "Placeholder" | "SmartArt" | "TextBox"
Comentários
Conjunto de APIs: PowerPointApi 1.4
Exemplos
// 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 se a forma é visível.
visible: boolean;
Valor da propriedade
boolean
Comentários
width
Especifica a largura, em pontos, da forma. Lança uma InvalidArgument exceção quando definido com um valor negativo.
width: number;
Valor da propriedade
number
Comentários
Conjunto de APIs: PowerPointApi 1.4
Exemplos
// 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
Retorna a posição de ordem z da forma, com 0 representando a parte inferior da pilha de pedidos. Todas as formas em um slide têm uma ordem z exclusiva, mas cada slide também tem uma pilha de ordem z exclusiva, portanto, duas formas em slides separados podem ter o mesmo número de ordem z.
readonly zOrderPosition: number;
Valor da propriedade
number
Comentários
Conjunto de APIs: PowerPointApi 1.8
Exemplos
// 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();
}
});
}
Detalhes do método
delete()
Exclui a forma da coleção de formas. Não fará nada se a forma não existir.
delete(): void;
Retornos
void
Comentários
Conjunto de APIs: PowerPointApi 1.3
Exemplos
// 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()
Observação
Esta API é fornecida como uma versão prévia para desenvolvedores e pode ser alterada com base nos comentários que recebemos. Não use esta API em um ambiente de produção.
Retorna um objeto PowerPoint.Graphic se essa forma é um ShapeType.graphic. Se essa forma não for um Graphic, um objeto com uma isNullObject propriedade definida como true será retornado. Para obter mais informações, consulte métodos e propriedades *OrNullObject.
getGraphicOrNullObject(): PowerPoint.Graphic;
Retornos
Comentários
getImageAsBase64(options)
Renderiza uma imagem da forma.
getImageAsBase64(options?: PowerPoint.ShapeGetImageOptions): OfficeExtension.ClientResult<string>;
Parâmetros
- options
- PowerPoint.ShapeGetImageOptions
Opcional. Opções para especificar as propriedades da imagem de saída desejadas.
Retornos
OfficeExtension.ClientResult<string>
Uma cadeia de caracteres codificada em Base64 da imagem da forma no formato especificado.
Comentários
Conjunto de APIs: PowerPointApi 1.10
Exemplos
// 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()
Retorna o objeto PowerPoint.Slide pai que contém esse Shapeobjeto . Lançará uma exceção se esta forma não pertencer a um .Slide
getParentSlide(): PowerPoint.Slide;
Retornos
Comentários
Conjunto de APIs: PowerPointApi 1.5
Exemplos
// 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()
Retorna o objeto PowerPoint.SlideLayout pai que contém esse Shapeobjeto . Lançará uma exceção se esta forma não pertencer a um .SlideLayout
getParentSlideLayout(): PowerPoint.SlideLayout;
Retornos
Comentários
getParentSlideLayoutOrNullObject()
Retorna o objeto PowerPoint.SlideLayout pai que contém esse Shapeobjeto . Se esta forma não pertencer a um SlideLayout, um objeto com uma isNullObject propriedade definida como true será retornado. Para obter mais informações, consulte métodos e propriedades *OrNullObject.
getParentSlideLayoutOrNullObject(): PowerPoint.SlideLayout;
Retornos
Comentários
getParentSlideMaster()
Retorna o objeto pai PowerPoint.SlideMaster que contém esse Shapeobjeto . Lançará uma exceção se esta forma não pertencer a um .SlideMaster
getParentSlideMaster(): PowerPoint.SlideMaster;
Retornos
Comentários
getParentSlideMasterOrNullObject()
Retorna o objeto pai PowerPoint.SlideMaster que contém esse Shapeobjeto . Se esta forma não pertencer a um SlideMaster, um objeto com uma isNullObject propriedade definida como true será retornado. Para obter mais informações, consulte métodos e propriedades *OrNullObject.
getParentSlideMasterOrNullObject(): PowerPoint.SlideMaster;
Retornos
Comentários
getParentSlideOrNullObject()
Retorna o objeto PowerPoint.Slide pai que contém esse Shapeobjeto . Se esta forma não pertencer a um Slide, um objeto com uma isNullObject propriedade definida como true será retornado. Para obter mais informações, consulte métodos e propriedades *OrNullObject.
getParentSlideOrNullObject(): PowerPoint.Slide;
Retornos
Comentários
getTable()
Retorna o Table objeto se essa forma for uma tabela.
getTable(): PowerPoint.Table;
Retornos
Comentários
Conjunto de APIs: PowerPointApi 1.8
Exemplos
// 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()
Retorna o objeto PowerPoint.TextFrame deste Shape. Se a forma não for compatível com um TextFrame, um objeto com uma isNullObject propriedade definida como true será retornado. Para obter mais informações, consulte métodos e propriedades *OrNullObject.
getTextFrameOrNullObject(): PowerPoint.TextFrame;
Retornos
Comentários
load(options)
Coloca um comando na fila para carregar as propriedades especificadas do objeto. Você deve chamar context.sync() antes de ler as propriedades.
load(options?: PowerPoint.Interfaces.ShapeLoadOptions): PowerPoint.Shape;
Parâmetros
Fornece opções para quais propriedades do objeto devem ser carregadas.
Retornos
load(propertyNames)
Coloca um comando na fila para carregar as propriedades especificadas do objeto. Você deve chamar context.sync() antes de ler as propriedades.
load(propertyNames?: string | string[]): PowerPoint.Shape;
Parâmetros
- propertyNames
-
string | string[]
Uma cadeia de caracteres delimitada por vírgula ou uma matriz de cadeias de caracteres que especifica as propriedades a serem carregadas.
Retornos
load(propertyNamesAndPaths)
Coloca um comando na fila para carregar as propriedades especificadas do objeto. Você deve chamar context.sync() antes de ler as propriedades.
load(propertyNamesAndPaths?: {
select?: string;
expand?: string;
}): PowerPoint.Shape;
Parâmetros
- propertyNamesAndPaths
-
{ select?: string; expand?: string; }
propertyNamesAndPaths.select é uma cadeia de caracteres delimitada por vírgula que especifica as propriedades a serem carregadas e propertyNamesAndPaths.expand é uma cadeia de caracteres delimitada por vírgula que especifica as propriedades de navegação a serem carregadas.
Retornos
setHyperlink(options)
Define um hiperlink com Shape as opções especificadas. Isso excluirá qualquer hiperlink existente neste Shape.
setHyperlink(options?: PowerPoint.HyperlinkAddOptions): PowerPoint.Hyperlink;
Parâmetros
- options
- PowerPoint.HyperlinkAddOptions
Opcional. As opções para o hiperlink.
Retornos
O objeto PowerPoint.Hyperlink recém-criado.
Comentários
Conjunto de APIs: PowerPointApi 1.10
Exemplos
// 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)
Move a forma especificada para cima ou para baixo na ordem z da coleção, que a desloca para frente ou para trás de outras formas.
setZOrder(position: PowerPoint.ShapeZOrder): void;
Parâmetros
- position
- PowerPoint.ShapeZOrder
Especifica como mover a forma dentro da pilha de ordem z. Usa a ShapeZOrder enumeração.
Retornos
void
Comentários
Conjunto de APIs: PowerPointApi 1.8
Exemplos
// 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)
Move a forma especificada para cima ou para baixo na ordem z da coleção, que a desloca para frente ou para trás de outras formas.
setZOrder(position: "BringForward" | "BringToFront" | "SendBackward" | "SendToBack"): void;
Parâmetros
- position
-
"BringForward" | "BringToFront" | "SendBackward" | "SendToBack"
Especifica como mover a forma dentro da pilha de ordem z. Usa a ShapeZOrder enumeração.
Retornos
void
Comentários
toJSON()
Substitui o método JavaScript toJSON() para fornecer uma saída mais útil quando um objeto de API é passado para JSON.stringify(). (JSON.stringify, por sua vez, chama o toJSON método do objeto que é passado para ele.) Enquanto o objeto original PowerPoint.Shape é um objeto de API, o toJSON método retorna um objeto JavaScript simples (digitado como PowerPoint.Interfaces.ShapeData) que contém cópias superficiais de todas as propriedades filho carregadas do objeto original.
toJSON(): PowerPoint.Interfaces.ShapeData;