簡體   English   中英

使用Apache POI在PowerPoint幻燈片中的兩點之間畫一條線

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

我開始認為我看不到明顯的東西。

給定以下代碼,我想從坐標[x1,y1]到[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>);

從中可以看到,線 [x1,y1]的錨點開始 ,但是隨后我必須輸入寬度和高度,而不是目標點的坐標。 但是目標坐標的y分量小於起始坐標的y分量,因此我嘗試將高度設置為負值,這會在PowerPoint嘗試打開生成的PPTX文檔時導致錯誤(“ PowerPoint發現內容存在問題文件out.pptx。 ”);

我敢肯定,我只是忽略了顯而易見的解決方案,因此有人可以幫助我找出如何在文檔中為一個點畫線到另一點嗎?

SetAnchor()采用AWT Rectangle2D ,實際上它並不關心您的寬度或高度是否為負(盡管負高度的矩形畢竟不是真正的對象,對嗎?)。 但是POI不會以這種方式解釋它,並且不幸的是,它不會拋出異常讓您知道。

據我了解,您只需要在x1x2y1y2之間選擇較低的起始坐標,以使正的寬度和高度與所需的端點一致。

像這樣:

// 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.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM