Рубрики
Без рубрики

Добавление, управление и удаление SmartArt в PowerPoint на Java

В этой статье показано, как добавлять, управлять и удалять SmartArt в документе PowerPoint на Java. Помеченный java, powerpoint, smartart.

Смарт-карта – это визуальное представление информации. В MS PowerPoint вы можете создавать множество различных типов макетов графики SmartArt для выражения своих идей. В этой статье я покажу вам, как добавлять, манипулировать и удалять SmartArt в документе PowerPoint программно на Java с помощью Free Spire. Презентация для Java API.

Добавление зависимостей

Прежде всего, вам нужно добавить необходимые зависимости для включения Free Spire. Презентация для Java в ваш Java-проект. Есть два способа сделать это. Если вы используете maven, вам необходимо добавить следующий код в свой проект pom.xml файл.

  
          
            com.e-iceblue  
            e-iceblue  
            http://repo.e-iceblue.com/nexus/content/groups/public/  
          
  
  
      
        e-iceblue  
        spire.presentation.free  
        2.6.1  
      

Для проектов, не связанных с maven, скачайте бесплатный Spire. Презентация для пакета Java с этого веб-сайта , распакуйте пакет и добавьте Spire.Presentation.jar в папке lib в вашем проекте в качестве зависимости.

Добавить SmartArt

Свободный дух. Презентация для Java API предоставляет shapeList.добавить SmartArt способ добавления SmartArt на слайд PowerPoint. В следующем примере показано, как добавить смарт-карту указанного типа макета в документ PowerPoint.

import com.spire.presentation.FileFormat;
import com.spire.presentation.ISlide;
import com.spire.presentation.Presentation;
import com.spire.presentation.diagrams.ISmartArt;
import com.spire.presentation.diagrams.SmartArtColorType;
import com.spire.presentation.diagrams.SmartArtLayoutType;
import com.spire.presentation.diagrams.SmartArtStyleType;

public class AddSmartArt {
    public static void main(String[] args) throws Exception {
        //Create a Presentation instance
        Presentation ppt = new Presentation();
        //Get the first slide
        ISlide slide = ppt.getSlides().get(0);

        //Add a SmartArt of a specified layout type to the slide
        ISmartArt smartArt = slide.getShapes().appendSmartArt(100,100, 400, 400, SmartArtLayoutType.BASIC_BLOCK_LIST);
        //Set the shape style of SmartArt
        smartArt.setStyle(SmartArtStyleType.CARTOON);
        //Set the color type of SmartArt
        smartArt.setColorStyle(SmartArtColorType.COLORFUL_ACCENT_COLORS);

        //Set text for the nodes in the SmartArt
        smartArt.getNodes().get(0).getTextFrame().setText("My SmartArt_1");
        smartArt.getNodes().get(1).getTextFrame().setText("My SmartArt_2");
        smartArt.getNodes().get(2).getTextFrame().setText("My SmartArt_3");
        smartArt.getNodes().get(3).getTextFrame().setText("My SmartArt_4");
        smartArt.getNodes().get(4).getTextFrame().setText("My SmartArt_5");

        //Save the result document
        ppt.saveToFile("AddSmartArt.pptx", FileFormat.PPTX_2013);
    }
}

Манипулировать умным искусством

Вы можете получить доступ к существующей смарт-карте и выполнить с ней ряд манипуляций, например, добавить/удалить узлы, отредактировать/извлечь текст, изменить стиль цвета/формы и т.д. Обратите внимание, что вы не можете изменить тип макета SmartArt, так как он доступен только для чтения и устанавливается только при добавлении формы SmartArt.

В следующем примере показано, как удалить узел из существующего SmartArt с помощью Коллекция ISmartArtNode.removenode метод.

import com.spire.presentation.FileFormat;
import com.spire.presentation.IShape;
import com.spire.presentation.ISlide;
import com.spire.presentation.Presentation;
import com.spire.presentation.diagrams.ISmartArt;

public class ManipulateSmartArt {
    public static void main(String[] args) throws Exception {
        //Create a Presentation instance
        Presentation ppt = new Presentation();
        //Load a PowerPoint document
        ppt.loadFromFile("AddSmartArt.pptx");

        //Get the first slide
        ISlide slide = ppt.getSlides().get(0);

        //Loop through the shapes on the slide
        for (Object shapeObj: slide.getShapes()) {
            IShape shape = (IShape)shapeObj;
            //Detect if the shape is SmartArt
            if(shape instanceof ISmartArt){
                ISmartArt smartArt = (ISmartArt)shape;
                //Remove the fifth node from the SmartArt
                smartArt.getNodes().removeNode(4);
                //do some other manipulations...
            }
        }

        //Save the result document
        ppt.saveToFile("ManipulateSmartArt.pptx", FileFormat.PPTX_2013);
    }
}

Удалить SmartArt

В следующем примере показано, как удалить все фигуры SmartArt на слайде PowerPoint с помощью Список фигур.удалить метод.

import com.spire.presentation.FileFormat;
import com.spire.presentation.IShape;
import com.spire.presentation.ISlide;
import com.spire.presentation.Presentation;
import com.spire.presentation.diagrams.ISmartArt;

public class DeleteSmartArt {
    public static void main(String[] args) throws Exception {
        //Create a Presentation instance
        Presentation ppt = new Presentation();
        //Load a PowerPoint document
        ppt.loadFromFile("AddSmartArt.pptx");

        //Get the first slide
        ISlide slide = ppt.getSlides().get(0);

        //Loop through the shapes on the slide
        for(int i = slide.getShapes().getCount()-1; i>=0; i--){
            IShape shape = slide.getShapes().get(i);
            //Detect if the shape is SmartArt
            if(shape instanceof  ISmartArt){
            //Remove the SmartArt
            slide.getShapes().remove(shape);
            }
        }

        //Save the result document
        ppt.saveToFile("DeleteSmartArt.pptx", FileFormat.PPTX_2013);
    }
}

Оригинал: “https://dev.to/eiceblue/add-manipulate-and-delete-smartart-in-powerpoint-in-java-195j”