简体   繁体   中英

Drawing a line between two points in PowerPoint slide using Apache POI

I'm starting to think I'm just not able to see the obvious.

Given the following code, I would like to draw a line from the coordinates [x1, y1] to [x2, y2].

int x1 = 20;
int y1 = 10;
int x2 = 30;
int y2 = 5;

XSLFSlide pptSlide = ...

XSLFAutoShape shape = pptSlide.createAutoShape();
shape.setShapeType(ShapeType.LINE);
shape.setAnchor(x1, y1, <width>, <height>);

From what I can see the line starts at the anchor of [x1, y1] but then I have to enter a width and height instead of the coordinates of the target point. But the y component of the target coordinate is less than that if the start coordinate so I tried setting the height to a negative values, which results in an error when PowerPoint tries to open the generated PPTX document (" PowerPoint found a problem with content in the file out.pptx. ");

I'm pretty sure I'm simply overlooking the obvious solution to this so can anybody help me in finding out how to draw a line for one point within the document to another point?

SetAnchor() takes an AWT Rectangle2D , which actually doesn't care if your width or height is negative (though a rectangle with negative height is not a real object after all, is it?). But POI doesn't interpret it that way, and unfortunately doesn't throw an exception to let you know.

As I understand your scenario, you just need to choose the lower starting coordinates between x1 and x2 , y1 and y2 so that a positive width and height agree with your desired endpoint.

Something like this:

// using Apache POI ooxml 3.17
static void drawBetweenTwoPoints(XSLFAutoShape shape, double x1, double x2, double y1, double y2) {
    shape.setAnchor(new Rectangle2D.Double(
            x1 <= x2 ? x1 : x2,  // choose the lowest x value
            y1 <= y2 ? y1 : y2,  // choose the lowest y value
            Math.abs(x2 - x1),   // get the actual width
            Math.abs(y2 - y1)    // get the actual height
    ));

    shape.setFlipVertical(y2 < y1);  // lines are drawn from rectangle top-left to 
                                     // bottom right by default.
                                     // When y2 is less than y1, flip the shape.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM