
// ReadSlidesText.java
// Andrew Davison, ad@coe.psu.ac.th, Nov. 2022

/* Print out all the text from the slides in a supplied Powerpoint 
   file.
   Compare this to Extractor.java

  Usage:
    > compile ReadSlidesText.java
    > run ReadSlidesText <pptx fnm>

    e.g.
    > run ReadSlidesText prelims.pptx
    but...
    > run ReadSlidesText file_example.ppt
    will trigger an exception since the file is PPT type
*/

import java.io.*;
import java.util.*;

import org.apache.poi.xslf.usermodel.*;


public final class ReadSlidesText
{

  public static void main(String[] args) 
  {
    if (args.length != 1) {
      System.out.println("Usage: run ReadSlidesText <pptx fnm>");
      System.exit(0);
    }
    String fnm = args[0];

    if (!POIUtils.isPowerPoint(fnm)) {
      System.out.println(fnm + " is not a PowerPoint file");
      System.exit(1);
    }
    if (POIUtils.isOldPowerPoint(fnm))
      System.out.println(fnm + " is an old-style PowerPoint file");

    try (FileInputStream fis = new FileInputStream(fnm)) {
      System.out.println("Reading from " + fnm);
      XMLSlideShow ppt = new XMLSlideShow(fis);

      StringBuilder sb = new StringBuilder();
      int slideNo = 1;
      for (XSLFSlide slide : ppt.getSlides()) {
        sb.append("\n----- Slide " + slideNo + " ---------\n");
        List<XSLFShape> shapes = slide.getShapes();
        for (XSLFShape shape : shapes) {
          if (shape instanceof XSLFTextShape) {
            XSLFTextShape textShape = (XSLFTextShape) shape;
            String text = textShape.getText();
            sb.append(text + "\n");
          }
          else if (shape instanceof XSLFPictureShape) {
            XSLFPictureShape pShape = (XSLFPictureShape) shape;
            XSLFPictureData pData = pShape.getPictureData();
            sb.append("Pic: " + pData.getFileName() + "\n");
          }
          else 
            sb.append("Shape: " + shape.getShapeName() + "\n");
        }
        slideNo++;
      }
      System.out.println(sb.toString());
    }
    catch (Exception e) 
    {   System.out.println(e);  }

  } /* main */

} // end of ReadSlidesText class
