通過Java后端代碼操作PPT幻燈片時,可直接在幻燈片中繪制形狀,並在形狀中添加文本字符串內容。本篇文章,介紹一種通過html字符串來添加內容到PPT幻燈片的的方法,可添加文字、圖片、視頻、音頻等。下面是具體方法和步驟。
一、 環境配置
- IntelliJ IDEA
- Free Spire.Presentation for Java
關於如何導入jar:
<repositories> <repository> <id>com.e-iceblue</id> <url>https://repo.e-iceblue.cn/repository/maven-public/</url> </repository> </repositories> <dependencies> <dependency> <groupId> e-iceblue </groupId> <artifactId>spire.presentation</artifactId> <version>3.9.0</version> </dependency> </dependencies>
2.手動從本地導入。下載Jar包到本地,解壓文件,找到lib文件夾下的jar文件。然后在IDEA中執行如圖操作:
二、代碼示例
代碼步驟解析:
l 實例化Presentation類的對象。
l 通過Presentation.getSlides().get(int)方法獲取指定幻燈片。
l 通過ISlide.getShapes().appendShape()添加形狀到幻燈片。
l 通過html字符串定義需要在形狀中添加的內容。
l 通過IAutoShape.getTextFrame().getParagraphs().addFromHtml()方法將html字符串添加到幻燈片。
l 最后通過Presentation.saveToFile()方法保存文檔。
Java
import com.spire.presentation.*; import com.spire.presentation.drawing.FillFormatType; import java.awt.*; public class AddHtmlCode { public static void main(String[] args)throws Exception { //實例化一個Presentation類的對象 Presentation ppt = new Presentation(); //獲取第一張幻燈片 ISlide slide = ppt.getSlides().get(0); //添加一個shape幻燈片 IAutoShape shape = slide.getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle(80, 50, 520, 180)); shape.getTextFrame().getParagraphs().clear(); shape.getFill().setFillType(FillFormatType.SOLID); shape.getFill().getSolidColor().setColor(Color.white); shape.getShapeStyle().getLineColor().setColor(Color.gray); //插入HTML到段落 String code = "<html>" + "<body>" + "<h1 style=\" color:darkGray \"> Hyper Text Markup Language (HTML) </h1>" + "<p style=\" color:darkGray ;font-size:20px \">即超文本標記語言。HTML是由Web的發明者 Tim Berners-Lee和同事 Daniel W. Connolly於1990年創立的一種標記語言,它是標准通用化標記語言SGML的應用。用HTML編寫的超文本文檔稱為HTML文檔,它能獨立於各種操作系統平台(如UNIX, Windows等)。</p>" + "</body>" + "</html>"; shape.getTextFrame().getParagraphs().addFromHtml(code); //保存文檔 String outputFile = "Result.pptx"; ppt.saveToFile(outputFile, FileFormat.PPTX_2013); } }
PPT幻燈片效果:
—End—