在本教程中,您将学习如何使用 Java 将 HTML 插入 PowerPoint。它解释了如何读取 HTML 文件的所有内容,然后使用它们将一张或多张幻灯片添加到演示文稿中。它还包含一个可运行的示例代码使用 Java 在 PowerPoint 中嵌入 HTML 然后将其保存为 PPTX、PPT 或 MS PowerPoint 支持的任何其他格式。
使用 Java 将 HTML 文件插入 PowerPoint 的步骤
- 建立环境添加Aspose.Slides for Java插入HTML内容
- 使用 FileInputStream 和 StringBuilder 类将 HTML 文件内容读入 String 变量
- 使用 Presentation 类创建新的 PowerPoint 演示文稿
- 获取对新创建的演示文稿的幻灯片集合的引用
- 使用 addFromHtml() 方法从 HTML 内容添加新幻灯片
- 将生成的演示文稿保存到磁盘
这些步骤总结了使用 Java* 将 HTML 插入 PowerPoint 的过程。首先,使用 FileInputStream 和 StringBuilder 类将 HTML 内容从文件中读取到一个字符串变量中,但是您可以从其他来源(如数据库、套接字或 Web API 等)获取内容。最后,这个字符串作为参数传递给 ISlideCollection.addFromHtml() 方法,用于根据 HTML 文件的大小向演示文稿添加幻灯片。
使用 Java 将 HTML 转换为 PowerPoint 的代码
import java.io.FileInputStream; | |
import com.aspose.slides.License; | |
import com.aspose.slides.Presentation; | |
import com.aspose.slides.SaveFormat; | |
public class AsposeTest { | |
public static void main(String[] args) throws Exception {//Main function to Insert HTML to PowerPoint using Java | |
// Instantiate the license | |
License lic = new License(); | |
lic.setLicense("Aspose.Total.lic"); | |
// Read HTML file contents into a string variable | |
FileInputStream fis = new FileInputStream("SampleInputForPresentation.html"); | |
byte[] buffer = new byte[10]; | |
StringBuilder sb = new StringBuilder(); | |
while (fis.read(buffer) != -1) { | |
sb.append(new String(buffer)); | |
buffer = new byte[10]; | |
} | |
fis.close(); | |
String htmlContents = sb.toString(); | |
// Create a new presentation | |
Presentation presentation = new Presentation(); | |
// Add a slide using the HTML contents | |
presentation .getSlides().addFromHtml(htmlContents); | |
// Save the output PowerPoint presentation as a PPTX | |
presentation.save("MyPresentation.pptx", SaveFormat.Pptx); | |
System.out.println("Done"); | |
} | |
} |
此代码演示如何使用 Java 在 PowerPoint 中插入 HTML。它使用 addFromHtml() 方法添加幻灯片,这些幻灯片采用包含 HTML 内容的单个字符串参数,而您可以直接提供 HTML 内容或使用其他采用不同参数的重载函数像一个流而不是一个字符串和一个 IExternalResourceResolver 对象来从特定的 URI 中获取外部内容。
本主题教会我们使用 Java 将 HTML 插入到 PowerPoint 中。如果您想将 PDF 内容插入演示文稿,请参阅 如何使用 Java 将 PDF 转换为演示文稿 上的文章。