用poi的XSLF创建ppt,添加文本的时候多了空行

来源:互联网 发布:sql存储过程怎么写 编辑:程序博客网 时间:2024/05/17 04:31

poi版本3.14.

根据poi的demo写了个简单的生成ppt的例子:

    public static void makePpt(String path) throws Exception {        if (path == null) {            path = "e:/text.pptx";        }        XMLSlideShow ppt = new XMLSlideShow();        XSLFSlide slide1 = ppt.createSlide();        XSLFTextBox shape1 = slide1.createTextBox();        Rectangle anchor = new Rectangle(10, 100, 300, 100);        shape1.setAnchor(anchor);        XSLFTextParagraph p1 = shape1.addNewTextParagraph();        XSLFTextRun r1 = p1.addNewTextRun();        r1.setFontColor(new Color(0, 200, 160));        shape1.setFillColor(Color.red);        r1.setText("text1");        XSLFTextBox shape2 = slide1.createTextBox();        Rectangle anchor2 = new Rectangle(210, 200, 300, 100);        shape2.setAnchor(anchor2);        shape2.setText("text2");        FileOutputStream out = new FileOutputStream(path);        ppt.write(out);        out.close();        ppt.close();    }
发现text1的文本框多了一个空行。text2文本框没有多空行。

使用如下代码看看到底生成了什么东西:

    public static void readPpt() throws Exception {        XMLSlideShow ppt = new XMLSlideShow(new FileInputStream("e:/text.pptx"));        XSLFSlide slide1 = ppt.getSlides().get(0);        for (XSLFShape shape : slide1.getShapes()) {            if (shape instanceof XSLFTextBox) {                XSLFTextBox box = (XSLFTextBox) shape;                java.util.List<XSLFTextParagraph> ps = box.getTextParagraphs();                if (ps.size() > 0) {                    java.util.List<XSLFTextRun> rs = ps.get(0).getTextRuns();                    if (!rs.isEmpty()) {                        System.out.println(rs.get(0).getRawText());                    }                }            }        }    }

发现shape1的那个XSLFTextBox其实有两个XSLFTextParagraph对象。

查看相应的代码,问题应该是出在XSLFTextParagraph p1 = shape1.addNewTextParagraph();这一句。原因应该是XSLFTextBox本身就有一个TextParagraph了。

这一行代码改成:

        XSLFTextParagraph p1 =shape1.getTextParagraphs().isEmpty() ?                shape1.addNewTextParagraph() : shape1.getTextParagraphs().get(0);

就可以了。




0 0
原创粉丝点击