Создание привлекательной презентации PowerPoint – это кропотливая работа, требующая сотрудничества мозга, глаз и рук. Чтобы добиться идеального эффекта, необходимо постоянно оттачивать детали, например, регулировать размер и положение фигуры или менять цвет текста. По этой причине создание документов PowerPoint вручную, как правило, более эффективно, чем использование кода. Однако в некоторых случаях нам может понадобиться сделать это программно.
В этой статье вы узнаете, как создать простой документ PowerPoint и вставить в него основные элементы (включая форму текста, форму изображения, список и таблицу) с помощью Free Spire.Presentation for Java, которая является бесплатной библиотекой классов для обработки документов PowerPoint в приложениях Java. Основные задачи этого учебника следующие.
- Создание документа PowerPoint
- Получить первый слайд и установить фоновое изображение
- Вставка текстовой фигуры
- Вставить фигуру изображения
- Вставить список
- Вставить таблицу
- Сохраните документ PowerPoint
Добавьте Spire.Presentation.jar в качестве зависимости
Если вы работаете над проектом maven, вы можете включить зависимость в файл pom.xml с помощью этой команды:
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.presentation.free</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>
Если вы не используете maven, то вы можете найти необходимые jar-файлы из zip-файла, доступного в этом месте. Включите все jar-файлы в папку lib приложения, чтобы запустить пример кода, приведенный в этом руководстве.
Импорт пространств имен
import com.spire.presentation.*;
import com.spire.presentation.drawing.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
Создание документа PowerPoint
//Create a Presentation object
Presentation presentation = new Presentation();
//Set the slide size type
presentation.getSlideSize().setType(SlideSizeType.SCREEN_16_X_9);
Получение первого слайда и установка фонового изображения
По умолчанию во вновь созданном документе PowerPoint имеется один пустой слайд.
//Get the first slide
ISlide slide = presentation.getSlides().get(0);
//Set the background image
String bgImage = "C:\Users\Administrator\Desktop\background.jpg";
BufferedImage image = ImageIO.read(new FileInputStream(bgImage));
IImageData imageData = slide.getPresentation().getImages().append(image);
slide.getSlideBackground().setType(BackgroundType.CUSTOM);
slide.getSlideBackground().getFill().setFillType(FillFormatType.PICTURE);
slide.getSlideBackground().getFill().getPictureFill().setFillType(PictureFillType.STRETCH);
slide.getSlideBackground().getFill().getPictureFill().getPicture().setEmbedImage(imageData);
Вставка текстовой фигуры
//Insert a text shape
Rectangle2D textBounds = new Rectangle2D.Float(50, 50, 440, 100);
IAutoShape textShape = slide.getShapes().appendShape(ShapeType.RECTANGLE, textBounds);
textShape.getFill().setFillType(FillFormatType.NONE);
textShape.getLine().setFillType(FillFormatType.NONE);
String text = "This article shows you how to create a PowerPoint document from scratch in Java using Spire.Presentation for Java. " +
"The following tasks are involved in this tutorial.";
TextFont titleFont = new TextFont("Calibri (Body)");
textShape.getTextFrame().setText(text);
//Set the text formatting
textShape.getTextFrame().getParagraphs().get(0).setAlignment(TextAlignmentType.LEFT);
PortionEx portionEx = textShape.getTextFrame().getTextRange().getParagraph().getFirstTextRange();
portionEx.getFill().setFillType(FillFormatType.SOLID);
portionEx.getFill().getSolidColor().setColor(Color.blue);
portionEx.setLatinFont(titleFont);
portionEx.setFontHeight(20f);
Вставка фигуры изображения
//Load an image
String imagePath = "C:\Users\Administrator\Desktop\java-logo.png";
Rectangle2D imageBounds = new Rectangle2D.Double(500, 80, 400, 200);
ShapeType shapeType = ShapeType.RECTANGLE;
BufferedImage bufferedImage = ImageIO.read(new FileInputStream(imagePath));
//Insert an image shape
IImageData iImageData = slide.getPresentation().getImages().append(bufferedImage);
IEmbedImage iEmbedImage = slide.getShapes().appendEmbedImage(shapeType, iImageData, imageBounds);
iEmbedImage.getLine().setFillType(FillFormatType.NONE);
iEmbedImage.getPictureFill().setFillType(PictureFillType.STRETCH);
Вставить список
//Insert a bulleted list
Rectangle2D listBounds = new Rectangle2D.Float(50, 160, 440, 180);
String[] listContent = new String[]{
" Create a PowerPoint Document",
" Set the background image",
" Insert a text shape",
" Insert an image shape",
" Insert a bulleted list",
" Insert a table",
" Save the PowerPoint document"
};
IAutoShape autoShape = slide.getShapes().appendShape(ShapeType.RECTANGLE, listBounds);
autoShape.getTextFrame().getParagraphs().clear();
autoShape.getFill().setFillType(FillFormatType.NONE);
autoShape.getLine().setFillType(FillFormatType.NONE);
for (int i = 0; i < listContent.length; i++) {
//Set the formatting of the list text
ParagraphEx paragraph = new ParagraphEx();
autoShape.getTextFrame().getParagraphs().append(paragraph);
paragraph.setText(listContent[i]);
paragraph.getTextRanges().get(0).getFill().setFillType(FillFormatType.SOLID);
paragraph.getTextRanges().get(0).getFill().getSolidColor().setColor(Color.black);
paragraph.getTextRanges().get(0).setLatinFont(new TextFont("Calibri (Body)"));
paragraph.getTextRanges().get(0).setFontHeight(20);
paragraph.setBulletType(TextBulletType.SYMBOL);
}
Вставить таблицу
//Define column widths and row heights
Double[] widths = new Double[]{100d, 100d, 100d, 150d, 100d, 100d};
Double[] heights = new Double[]{15d, 15d, 15d, 15d};
//Add a table
ITable table = presentation.getSlides().get(0).getShapes().appendTable(50, 350, widths, heights);
//Define table data
String[][] data = new String[][]{
{"Emp#", "Name", "Job", "HiringD", "Salary", "Dept#"},
{"7369", "Andrews", "Engineer", "05/12/2021", "1600.00", "20"},
{"7499", "Nero", "Technician", "03/23/2021", "1800.00", "30"},
{"7566", "Martin", "Manager", "12/21/2021", "2600.00", "10"},
};
//Loop through the row and column of the table
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
//Fill the table with data
table.get(j, i).getTextFrame().setText(data[i][j]);
//Align text in each cell to center
table.get(j, i).getTextFrame().getParagraphs().get(0).setAlignment(TextAlignmentType.CENTER);
}
}
//Apply a built-in style to table
table.setStylePreset(TableStylePreset.LIGHT_STYLE_1_ACCENT_4);
Сохранить документ PowerPoint
//Save to file
presentation.saveToFile("output/CreatePowerPoint.pptx", FileFormat.PPTX_2013);
Вывод