1.添加依赖
<dependencies><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>5.2.3</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>5.2.3</version></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itext7-core</artifactId><version>7.2.2</version></dependency>
</dependencies>
2.示例代码
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFShape;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;public class PptToPdfConverter {public static void main(String[] args) {String pptFilePath = "input.pptx"; // 输入的PPT文件路径String pdfFilePath = "output.pdf"; // 输出的PDF文件路径try {convertPptToPdf(pptFilePath, pdfFilePath);System.out.println("转换成功!");} catch (IOException e) {e.printStackTrace();}}private static void convertPptToPdf(String pptFilePath, String pdfFilePath) throws IOException {XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(pptFilePath));PdfWriter writer = new PdfWriter(new FileOutputStream(pdfFilePath));PdfDocument pdfDoc = new PdfDocument(writer);Document pdfDocument = new Document(pdfDoc);
// 设置中文字体PdfFont font = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", true);for (XSLFSlide slide : ppt.getSlides()) {StringBuilder slideContent = new StringBuilder();for (XSLFShape shape : slide.getShapes()) {slideContent.append(shape.getText()).append("\n");}pdfDocument.add(new Paragraph(slideContent.toString()).setFont(font));}pdfDocument.close();pdfDoc.close();ppt.close();}
}
- Apache POI + PDFBox适合简单需求,但对复杂文档支持有限。
- 处理复杂的PPT文档,可以使用商业版的Aspose.Slides