PPT to PNG conversion with Apache POI

2019-05-24 11:50发布

问题:

By following the example provided at http://poi.apache.org/slideshow/how-to-shapes.html i got the conversion to work.

FileInputStream is = new FileInputStream("slideshow.ppt");
SlideShow ppt = new SlideShow(is);
is.close();

Dimension pgsize = ppt.getPageSize();

Slide[] slide = ppt.getSlides();
for (int i = 0; i < slide.length; i++){

    BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics = img.createGraphics();

    graphics.setPaint(Color.white);
    graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
    slide[i].draw(graphics);
    FileOutputStream out = new FileOutputStream("slide-"  + (i+1) + ".png");
    javax.imageio.ImageIO.write(img, "png", out);
    out.close();
}

However the generated images are very small. How do increase the size of the image output?

回答1:

You need to resize the graphics context and add a general transformation.

    FileInputStream is = new FileInputStream("slideshow.pptx");
    SlideShow ppt = new SlideShow(is);
    is.close();

    double zoom = 2; // magnify it by 2
    AffineTransform at = new AffineTransform();
    at.setToScale(zoom, zoom);

    Dimension pgsize = ppt.getPageSize();

    Slide[] slide = ppt.getSlides();
    for (int i = 0; i < slide.length; i++) {
        BufferedImage img = new BufferedImage((int)Math.ceil(pgsize.width*zoom), (int)Math.ceil(pgsize.height*zoom), BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = img.createGraphics();
        graphics.setTransform(at);

        graphics.setPaint(Color.white);
        graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
        slide[i].draw(graphics);
        FileOutputStream out = new FileOutputStream("slide-" + (i + 1) + ".png");
        javax.imageio.ImageIO.write(img, "png", out);
        out.close();
    }