В этой статье описывается, как добавить SmartArt в PowerPoint с помощью Java REST API. Вы научитесь автоматически вставлять PowerPoint SmartArt с Java Low Code API с помощью Cloud SDK на основе Java. Обсуждаются различные классы и перечислители для создания различных типов SmartArt на слайде презентации PowerPoint.
Обязательное условие
Скачать Aspose.Slides Cloud SDK for Java for inserting SmartArt in slides
Настройте проект Java с помощью вышеуказанного SDK для создания графики SmartArt.
Действия по добавлению SmartArt презентации PowerPoint с помощью Java REST API
- Установите учетные данные в объекте SlidesApi для работы со SmartArt.
- Загрузите исходную презентацию в Облачное хранилище для вставки смарт-графики.
- Создайте графические данные, задав нужные свойства в объекте SmartArt.
- Вставьте SmartArt, используя метод CreateShape().
- Загрузите обновленный файл презентации после добавления в него SmartArt.
Эти шаги объясняют, как работать с SmartArt для PowerPoint с помощью Java REST API. Создайте объект класса SlidesApi, загрузите исходную презентацию и создайте объект SmartArt с указанными настройками, включая положение, размер, макет, быстрый стиль и цветовой стиль. Наконец, к соответствующему слайду добавляются несколько узлов для SmartArt с помощью метода CreateShape().
Код для добавления смарт-фигур PowerPoint с помощью Java API на основе Java
import com.aspose.slides.ApiException; | |
import com.aspose.slides.api.SlidesApi; | |
import com.aspose.slides.model.*; | |
import java.io.File; | |
import java.io.IOException; | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.nio.file.StandardCopyOption; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class Example_AddSmartArtShapeInPresentation { | |
protected static SlidesApi presentationApi; | |
public Example_AddSmartArtShapeInPresentation() { | |
if (presentationApi == null) { | |
presentationApi = new SlidesApi("appSid", "appKey"); | |
} | |
} | |
public void addCustomShapeInSlide() throws ApiException, IOException { | |
String localPath = "/home/downloads/"; | |
String fileName = "Sample.pptx"; | |
String imageFileName = "ShapeImage.png"; | |
String storageFolderName = "TempTests"; | |
presentationApi.uploadFile(storageFolderName+"/"+fileName, readFileToByteArray(localPath + fileName),null); | |
// Configure SmartArt properties | |
SmartArt smartArt = new SmartArt(); | |
smartArt.setX(50.0); // Horizontal position of the SmartArt | |
smartArt.setY(50.0); // Horizontal position of the SmartArt | |
smartArt.setWidth(250.0); // Width of the SmartArt | |
smartArt.setHeight(250.0); // Height of the SmartArt | |
smartArt.setLayout(SmartArt.LayoutEnum.BENDINGPICTURESEMITRANSPARENTTEXT); // SmartArt layout | |
smartArt.setQuickStyle(SmartArt.QuickStyleEnum.SIMPLEFILL); // Quick style | |
smartArt.setColorStyle(SmartArt.ColorStyleEnum.COLOREDFILLACCENT1); // Color style | |
List<SmartArtNode> nodes = new ArrayList<SmartArtNode>(); | |
SmartArtNode node1 = new SmartArtNode(); | |
node1.setText("Planning"); | |
nodes.add(node1); | |
SmartArtNode node2 = new SmartArtNode(); | |
node2.setText("Design"); | |
nodes.add(node2); | |
SmartArtNode node3 = new SmartArtNode(); | |
node3.setText("Implementation"); | |
nodes.add(node3); | |
smartArt.setNodes(nodes); | |
// Add SmartArt to the first slide | |
ShapeBase addedSmartArt = presentationApi.createShape(fileName, 1, smartArt, null, null, null, storageFolderName, null, null ); | |
System.out.println("SmartArt added to the presentation successfully."); | |
File presentationFile = presentationApi.downloadFile(storageFolderName+"/"+fileName, null, null); | |
// Copy the downloaded presentation with new image shape to the local directory | |
copyFile(presentationFile, new File(localPath, fileName)); | |
System.out.println("Presentation slide with SmartArt shape is copied to: " + localPath + fileName); | |
} | |
public static byte[] readFileToByteArray(String filePath) throws IOException { | |
Path path = new File(filePath).toPath(); | |
return Files.readAllBytes(path); | |
} | |
private void copyFile(File sourceFile, File targetFile) throws IOException { | |
if (sourceFile == null || !sourceFile.exists()) { | |
throw new IOException("Source file does not exist: " + sourceFile); | |
} | |
// Ensure the target directory exists | |
Path targetPath = targetFile.toPath(); | |
Files.createDirectories(targetPath.getParent()); | |
// Copy the file | |
Files.copy(sourceFile.toPath(), targetPath, StandardCopyOption.REPLACE_EXISTING); | |
} | |
} |
Этот код демонстрирует, как вставить графику Smart Art с интерфейсом Java REST на слайд. Используйте LayoutEnum, чтобы выбрать нужную фигуру SmartArt из большого списка значений, включая AccentProcess, AccentedPicture, ArrowRibbon, BasicPyramid, BasicProcess и т. д. Аналогично, перечислители быстрого стиля и цветового стиля также имеют множество параметров для настройки SmartArt.
Эта статья научила нас создавать SmartArt на слайде презентации. Сведения о добавлении пользовательских фигур в презентацию см. в статье Создание пользовательских фигур в PowerPoint с помощью Java REST API.