PowerPoint是可以制做出集文字、图形、声音以及视频剪辑等多媒体元素于一体的演示文稿,所以,经过PPT能够将所需表达的内容直观、形象地展现给他人。考虑到彻底经过Java程序来全新建立出精美的PPT文稿比较耗时,建议可先使用MS PPT来建立一个模板,其次再经过Java程序替换模板中的文本和图片,以此既节约时间,同时又能呈现完美效果。因此,本文着重介绍经过Java程序来演示如何替换PPT文档中已有的文本和图片。html
方法1:经过官网下载获取jar包。解压后将lib文件夹下的Spire.Presentation.jar文件导入Java程序。(以下图)java
方法2:经过maven仓库安装导入。具体安装详解参见此网页。app
首先,在此建立了一张含有图片及文本信息的PPT幻灯片模板。(以下图)对模板中的文本能够预先设置好字体、字号和颜色等样式,以便被替换进文档的新文本可以保留想要的格式。maven
import com.spire.presentation.*; import java.util.HashMap; import java.util.Map; public class ReplaceText { public static void main(String[] args) throws Exception { //建立Presentation对象 Presentation presentation = new Presentation(); //加载示例文档 presentation.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pptx"); //获取第一张幻灯片 ISlide slide= presentation.getSlides().get(0); //建立Map对象 Map<String, String> map = new HashMap<String, String>(); //将须要被替换和用于替换的文本以键值的形式添加到Map map.put("#景点名称#","北京故宫"); map.put("#地理位置#","北京,中国"); String description = " 北京故宫是中国明清两代的皇家宫殿,旧称紫禁城,位于北京中轴线的中心," + "是中国古代宫廷建筑之精华。北京故宫以三大殿为中心,占地面积72万平方米,建筑面积约15万平方米," + "有大小宫殿七十多座,房屋九千余间。是世界上现存规模最大、保存最为完整的木质结构古建筑之一。"; map.put("#基本信息#",description); //替换幻灯片中的文本 replaceText(slide,map); //保存文档 presentation.saveToFile("output/ReplaceText.pptx", FileFormat.PPTX_2013); } /** * 替换指定幻灯片中的文本 * @param slide指定幻灯片 * @param map以键值的形式存储须要被替换和用于替换的文本 */ public static void replaceText(ISlide slide, Map<String, String> 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))); } } } } } } }
文本替换效果:ide
import com.spire.presentation.*; import com.spire.presentation.drawing.IImageData; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.FileInputStream; import java.io.FileNotFoundException; public class ReplaceImage { public static void main(String[] args) throws Exception { //建立Presentation对象 Presentation presentation= new Presentation(); //加载PowerPoint示例文档 presentation.loadFromFile("C:\\Users\\Test1\\Desktop\\ReplaceText.pptx"); //添加图片到图片集合 String imagePath ="C:\\Users\\Test1\\Desktop\\Image.png"; BufferedImage bufferedImage = ImageIO.read(new FileInputStream(imagePath)); IImageData image = presentation.getImages().append(bufferedImage); //获取第一张幻灯片上形状集合 ShapeCollection shapes = presentation.getSlides().get(0).getShapes(); //遍历全部形状 for (int i = 0; i < shapes.getCount(); i++) { //判断形状是不是图片 if (shapes.get(i) instanceof SlidePicture) { //将第一张图片用新图片填充 ((SlidePicture)shapes.get(i)).getPictureFill().getPicture().setEmbedImage(image); break; } } //保存文档 presentation.saveToFile("output/ReplaceImage.pptx", FileFormat.PPTX_2013); } }
图片替换效果:工具
(本文完)字体