PowerPoint JS API: connect 2 rectangles

44 views Asked by At

I can't find any reference on how to connect 2 shapes in PowerPoint using their JS API for Office Add-in (using latest version as of 03.2024).

Here is my simple code:

export async function run() {
  await PowerPoint.run(async (context) => {
    const shapes = 
    context.presentation.slides.getItemAt(0).shapes; // Get the first slide

    // Create rectangle 1
    const rectangle1 =  shapes.addGeometricShape(PowerPoint.GeometricShapeType.rectangle);
    rectangle1.left = 100;
    rectangle1.top = 50;
    rectangle1.height = 150;
    rectangle1.width = 50;
    rectangle1.name = "Rectangle1";

    // Create rectangle 2
    const rectangle2 = shapes.addGeometricShape(PowerPoint.GeometricShapeType.rectangle);
    rectangle2.left = 300;
    rectangle2.top = 50;
    rectangle2.height = 150;
    rectangle2.width = 100;
    rectangle2.name = "Rectangle2";

    const line = shapes.addLine(
    PowerPoint.ConnectorType.straight, 
    { left: 150, 
      top: 125, 
      height: -1 /**another great move MS! why 0 is not working?**/, 
      width: 150 
    });
    line.name = "StraightLine";

    await context.sync();
  });
}

Result of this code and How it should be

What do I mean by connecting - link

How do I connect them with a line?

1

There are 1 answers

7
Rick Kirkham On

Use the ShapeCollection.addLine method. Here's an example:

// 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();
});