Создание документа PowerPoint с нуля может занять довольно много времени. Это становится еще сложнее, если вам удастся создать хорошо продуманный документ полностью с помощью java-кода. Поэтому мы рекомендуем предварительно разработать шаблон с помощью MS PowerPoint, а затем заменить текст и изображения в нем с помощью Free Spire. Презентация для Java . Поступая таким образом, вы можете сэкономить некоторое время и в некоторой степени автоматизировать процесс. В следующих разделах будет продемонстрировано то же самое.
Создание шаблона
Как показано ниже, мы подготовили простой шаблон, содержащий одно изображение и несколько фрагментов текста. Текст был отформатирован с использованием цвета шрифта, размера шрифта и названия шрифта, так что новый текст, замененный в документе, сохраняет желаемый стиль.
Добавление Jar в проект
Шаг 1. Скачать Бесплатный Шпиль. Презентация для Java пакет, распакуйте его. Ты найдешь Спайра.Презентация.файл jar в папке lib.
Шаг 2. Создайте проект java в ваших ГЛАЗАХ и добавьте файл jar в качестве зависимости. Вот как это выглядит в IntelliJ IDEA.
Использование кода
Часть 1. Заменить Текст
import com.spire.presentation.*;
import java.util.HashMap;
import java.util.Map;
public class ReplaceText {
public static void main(String[] args) throws Exception {
//create a Presentation object
Presentation presentation = new Presentation();
//load the template file
presentation.loadFromFile("C:\\Users\\Administrator\\Desktop\\template.pptx");
//get the first slide
ISlide slide= presentation.getSlides().get(0);
//create a Map object
Map map = new HashMap();
//add several pairs of keys and values to the map
map.put("#cityName#","Chengdu");
map.put("#location#","Sichuan Province, China");
String description = "Chengdu, formerly romanized as Chengtu, is a sub-provincial city which serves as the capital "+
"of China's Sichuan province. It is one of the three most populous cities in Western China . As of 2014, "+
"the administrative area houses 14,427,500 inhabitants, with an urban population of 10,152,632. At the time "+
"of the 2010 census, Chengdu was the 5th-most populous agglomeration in China, with 10,484,996 inhabitants "+
"in the built-up area including Xinjin County and Deyang's Guanghan City.";
map.put("#description#",description);
map.put("#popular#","Museum, Landmark, Religious Sites, Architecture, Parks");
//replace text in the slide
replaceText(slide,map);
//save to another file
presentation.saveToFile("output/ReplaceText.pptx", FileFormat.PPTX_2013);
}
/**
* Replace text within a slide
* @param slide Specifies the slide where the replacement happens
* @param map Where keys are existing strings in the document and values are the new strings to replace the old ones
*/
public static void replaceText(ISlide slide, Map map) {
for (Object shape : slide.getShapes()
) {
if (shape instanceof IAutoShape) {
for (Object paragraph : ((IAutoShape) shape).getTextFrame().getParagraphs()
) {
ParagraphEx paragraphEx = (ParagraphEx)paragraph;
for (String key : map.keySet()
) {
if (paragraphEx.getText().contains(key)) {
paragraphEx.setText(paragraphEx.getText().replace(key, map.get(key)));
}
}
}
}
}
}
}
Часть 2. Заменить изображение
import com.spire.presentation.*;
import com.spire.presentation.drawing.IImageData;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
public class ReplaceImage {
public static void main(String[] args) throws Exception {
//create a Presentation object
Presentation presentation= new Presentation();
//load the documenet generted by above code
presentation.loadFromFile("C:\\Users\\Administrator\\Desktop\\ReplaceText.pptx");
//add an image to the image collection
String imagePath = "C:\\Users\\Administrator\\Desktop\\Chengdu.jpeg";
BufferedImage bufferedImage = ImageIO.read(new FileInputStream(imagePath));
IImageData image = presentation.getImages().append(bufferedImage);
//get the shape collection from the first slide
ShapeCollection shapes = presentation.getSlides().get(0).getShapes();
//loop through the shape collection
for (int i = 0; i < shapes.getCount(); i++) {
//determine if a shape is a picture
if (shapes.get(i) instanceof SlidePicture) {
//fill the shape with a new image
((SlidePicture) shapes.get(i)).getPictureFill().getPicture().setEmbedImage(image);
}
}
//save to file
presentation.saveToFile("output/ReplaceImage.pptx", FileFormat.PPTX_2013);
}
}
Оригинал: “https://dev.to/eiceblue/replace-text-and-images-in-powerpoint-in-java-1ibj”