Продвинутое извлечение текста из презентаций на PHP

Извлечение текста со слайдов

Aspose.Slides for PHP via Java provides the SlideUtil class. This class exposes a number of overloaded static methods for extracting the entire text from a presentation or slide. To extract the text from a slide in a PPTX presentation, use the getAllTextBoxes overloaded static method exposed by the SlideUtil class. This method accepts the Slide object as a parameter. Upon execution, the Slide method scans the entire text from the slide passed as parameter and returns an array of TextFrame objects. This means that any text formatting associated with the text is available. The following piece of code extracts all the text on the first slide of the presentation:

  # Создать экземпляр класса Presentation, представляющего файл PPTX
  $pres = new Presentation("demo.pptx");
  $Array = new java_class("java.lang.reflect.Array");
  try {
    foreach($pres->getSlides() as $slide) {
      # Получить массив объектов ITextFrame со всех слайдов в PPTX
      $textFramesPPTX = SlideUtil->getAllTextBoxes($slide);
      # Перебрать массив TextFrames
      for($i = 0; $i < java_values($Array->getLength($textFramesPPTX)) ; $i++) {
        # Перебрать абзацы в текущем ITextFrame
        foreach($textFramesPPTX[$i]->getParagraphs() as $para) {
          # Перебрать части в текущем IParagraph
          foreach($para->getPortions() as $port) {
            # Отобразить текст в текущей части
            echo($port->getText());
            # Отобразить высоту шрифта текста
            echo($port->getPortionFormat()->getFontHeight());
            # Отобразить название шрифта текста
            if (!java_is_null($port->getPortionFormat()->getLatinFont())) {
              echo($port->getPortionFormat()->getLatinFont()->getFontName());
            }
          }
        }
      }
    }
  } finally {
    $pres->dispose();
  }

Извлечение текста из презентаций

To scan the text from the whole presentation, use the getAllTextFrames static method exposed by the SlideUtil class. It takes two parameters:

  1. First, a Presentation object that represents the presentation from which the text is being extracted.
  2. Second, a boolean value determining whether the master slide is to be included when the text is scanned from the presentation. The method returns an array of TextFrame objects, complete with text formatting information. The code below scans the text and formatting information from a presentation, including the master slides.
  # Создать экземпляр класса Presentation, представляющего файл PPTX
  $pres = new Presentation("demo.pptx");
  $Array = new java_class("java.lang.reflect.Array");
  try {
    # Получить массив объектов ITextFrame со всех слайдов в PPTX
    $textFramesPPTX = SlideUtil->getAllTextFrames($pres, true);
    # Перебрать массив TextFrames
    for($i = 0; $i < java_values($Array->getLength($textFramesPPTX)) ; $i++) {
      # Перебрать абзацы в текущем ITextFrame
      foreach($textFramesPPTX[$i]->getParagraphs() as $para) {
        # Перебрать части в текущем IParagraph
        foreach($para->getPortions() as $port) {
          # Отобразить текст в текущей части
          echo($port->getText());
          # Отобразить высоту шрифта текста
          echo($port->getPortionFormat()->getFontHeight());
          # Отобразить название шрифта текста
          if (!java_is_null($port->getPortionFormat()->getLatinFont())) {
            echo($port->getPortionFormat()->getLatinFont()->getFontName());
          }
        }
      }
    }
  } finally {
    $pres->dispose();
  }

Категоризированное и быстрое извлечение текста

The new static method getPresentationText has been added to Presentation class. There are three overloads for this method:


The TextExtractionArrangingMode enum argument indicates the mode to organize the output of text result and can be set to the following values:

  • Unarranged - The raw text with no respect to position on the slide
  • Arranged - The text is positioned in the same order as on the slide

Unarranged mode can be used when speed is critical, it’s faster than Arranged mode.

IPresentationText represents the raw text extracted from the presentation. It contains a getSlidesText method which returns an array of ISlideText objects. Every object represent the text on the corresponding slide. ISlideText object have the following methods:

There is also a SlideText class which implements the ISlideText interface.

The new API can be used like this:

  $text1 = PresentationFactory->getInstance()->getPresentationText("presentation.pptx", TextExtractionArrangingMode->Unarranged);
  echo($text1->getSlidesText()[0]->getText());
  echo($text1->getSlidesText()[0]->getLayoutText());
  echo($text1->getSlidesText()[0]->getMasterText());
  echo($text1->getSlidesText()[0]->getNotesText());

FAQ

Как быстро Aspose.Slides обрабатывает большие презентации при извлечении текста?

Aspose.Slides оптимизирован для высокой производительности и эффективно обрабатывает даже large presentations, что делает его подходящим для сценариев реального времени или массовой обработки.

Может ли Aspose.Slides извлекать текст из таблиц и диаграмм внутри презентаций?

Да, Aspose.Slides полностью поддерживает извлечение текста из таблиц, диаграмм и других сложных элементов слайда, позволяя легко получать и анализировать весь текстовый контент.

Нужна ли особая лицензия Aspose.Slides для извлечения текста из презентаций?

Вы можете извлекать текст с помощью бесплатной пробной версии Aspose.Slides, хотя она имеет определённые ограничения, например, обработку только ограниченного количества слайдов. Для неограниченного использования и работы с более крупными презентациями рекомендуется приобрести полную лицензию.