pptx转pdf工具类

引入依赖

      
        org.apache.poi
        poi
        5.0.0
      

      
        org.apache.poi
        poi-ooxml
        5.0.0
      

      
        org.apache.pdfbox
        pdfbox
        3.0.0-RC1
      

工具类

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.poi.xslf.usermodel.*;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
public class FileConvertUtil {
 public static void convertPPTXtoPDF(String pptxFilePath, String pdfFilePath) {
    try (FileInputStream inputStream = new FileInputStream(pptxFilePath);
         FileOutputStream outputStream = new FileOutputStream(pdfFilePath)) {

      XMLSlideShow pptx = new XMLSlideShow(inputStream);

      PDDocument pdfDoc = new PDDocument();
      File imageTempDir = Files.createTempDirectory("pptx_to_pdf").toFile();

      int pageNum = 0;
      for (XSLFSlide slide : pptx.getSlides()) {

        for (XSLFShape shape : slide.getShapes()) {
          if (shape instanceof XSLFTextShape) {
            XSLFTextShape textShape = (XSLFTextShape) shape;
            for (XSLFTextParagraph textParagraph : textShape.getTextParagraphs()) {
              for (XSLFTextRun textRun : textParagraph.getTextRuns()) {
                textRun.setFontFamily("宋体");
              }
            }
          }
        }


        Dimension pageSize = pptx.getPageSize();
        BufferedImage bufferedImage = new BufferedImage(pageSize.width, pageSize.height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = bufferedImage.createGraphics();
        graphics.setPaint(Color.white);
        graphics.fill(new Rectangle(pageSize));

        slide.draw(graphics);

        File imageFile = new File(imageTempDir, "slide_" + pageNum + ".png");
        ImageIO.write(bufferedImage, "png", imageFile);

        PDPage pdfPage = new PDPage(new org.apache.pdfbox.pdmodel.common.PDRectangle(pageSize.width, pageSize.height));
        pdfDoc.addPage(pdfPage);

        try (PDPageContentStream contentStream = new PDPageContentStream(pdfDoc, pdfPage)) {
          PDImageXObject pdfImage = PDImageXObject.createFromByteArray(pdfDoc, Files.readAllBytes(imageFile.toPath()), "slide_" + pageNum);
          contentStream.drawImage(pdfImage, 0, 0);
        }

        pageNum++;
      }

      pdfDoc.save(outputStream);
      pdfDoc.close();

      // Delete temporary image files
      for (File imageFile : imageTempDir.listFiles()) {
        imageFile.delete();
      }
      imageTempDir.delete();

      System.out.println("PPTX to PDF conversion completed successfully.");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

你可能感兴趣的:(powerpoint)