如何将背景图像添加到使用apache poi生成的幻灯片?

时间:2017-03-07 16:33:35

标签: java apache apache-poi powerpoint

是否可以将背景图像添加到使用apache poi生成的幻灯片中? 这是我的代码 -

    try {
        // create a ppt
        XMLSlideShow ppt = new XMLSlideShow();
        XSLFSlideMaster slideMaster = ppt.getSlideMasters().get(0);
        XSLFSlideLayout slidelayout = slideMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);      

        // create a slide
        XSLFSlide slide = ppt.createSlide(slidelayout);

        // add bg image         
        File imageFile = new File("image1.jpg");
        InputStream is = new FileInputStream(imageFile);
        BufferedImage image = ImageIO.read(is);
        float w = image.getWidth();
        float h = image.getHeight();
        Rectangle2D r2d = new Rectangle2D.Float(0, 0, w, h);
        slide.getBackground().draw(image.createGraphics(), r2d);

        //create a file object
        File file = new File("pres.pptx");
        FileOutputStream out = new FileOutputStream(file);
        ppt.write(out);
        ppt.close();

        System.out.println("slide generated!");
        out.close();
    } catch(Exception e) {
        e.printStackTrace();
    }

文件生成成功,但没有背景图片,该怎么办?

Screenshot of my slide

1 个答案:

答案 0 :(得分:1)

设置背景,即幻灯片主图像,远不是您的解决方案,但使用draw()方法的目的完全不同。
(用POI 3.16-beta1测试)

import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileOutputStream;

import org.apache.poi.sl.usermodel.PictureData.PictureType;
import org.apache.poi.xslf.usermodel.SlideLayout;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFAutoShape;
import org.apache.poi.xslf.usermodel.XSLFPictureData;
import org.apache.poi.xslf.usermodel.XSLFPictureShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFSlideLayout;
import org.apache.poi.xslf.usermodel.XSLFSlideMaster;

public class BgFill {
    public static void main(String[] args) throws Exception {
        // create a ppt
        XMLSlideShow ppt = new XMLSlideShow();
        XSLFPictureData pd = ppt.addPicture(new File("wrench.emf"), PictureType.EMF);
        XSLFSlideMaster slideMaster = ppt.getSlideMasters().get(0);
        XSLFSlideLayout slidelayout = slideMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);
        XSLFPictureShape ps = slidelayout.createPicture(pd);
        ps.setAnchor(new Rectangle2D.Double(100, 100, 400, 400));

        XSLFSlide sl = ppt.createSlide(slidelayout);
        ((XSLFAutoShape)sl.getShapes().get(0)).setText("title");
        ((XSLFAutoShape)sl.getShapes().get(1)).setText("content");

        FileOutputStream fos = new FileOutputStream("bla.pptx");
        ppt.write(fos);
        fos.close();
    }
}