Java POI实现ppt&pptx转换为pdf文件

Java POI实现ppt&pptx转换为pdf文件

背景

需求使用ppt&pptx 上传文件转换为PDF文件,方便前端展示

区别

PPTPPTX
MS Office PowerPoint2003之前版本MS Office PowerPoint2007之后的版本生成
基于二进制的文件pptx是基于xml文件
POI 中HSLFSlideShow处理POI 中XMLSlideShow处理

参考博客

java 实现 ppt或pptx文件转换PDF文件 – poi

代码

依赖

		<!--  poi -->
	    <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.15</version>
        </dependency>

		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.15</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-scratchpad</artifactId>
			<version>3.15</version>
		</dependency>
		
       <!-- itextpdf -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.4.3</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

工具类

与参考博客差不多。做了一些细小处理

package com.fang.industry.service.common.utils;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xslf.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.hslf.usermodel.*;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.Image;
/**
 * @author: guochao.bj@fang.com
 * @createDate: 2021/11/30 13:52
 */
public class PdfConverUtil {


    public static boolean pptxToPdf(String pptPath, String pdfDir) {

        if (StringUtils.isEmpty(pptPath)) {
            throw new RuntimeException("word文档路径不能为空");
        }

        if (StringUtils.isEmpty(pdfDir)) {
            throw new RuntimeException("pdf目录不能为空");
        }

        String pdfPath = pdfDir + "te." + "pdf";

        Document document = null;

        XMLSlideShow slideShow = null;


        FileOutputStream fileOutputStream = null;

         PdfWriter pdfWriter = null;


        try {
            //使用输入流pptx文件
            slideShow = new XMLSlideShow(new FileInputStream(pptPath));
            //获取幻灯片的尺寸
            Dimension dimension = slideShow.getPageSize();
            //新增pdf输出流,准备讲ppt写出
            fileOutputStream = new FileOutputStream(pdfPath);
            //创建一个写内容的容器
            document = new Document();
            //使用输出流写入
            pdfWriter = PdfWriter.getInstance(document, fileOutputStream);
            //使用之前必须打开<You have to open the document before you can write content.>
            document.open();

            PdfPTable pdfPTable = new PdfPTable(1);
            //获取幻灯片
            List<XSLFSlide> slideList = slideShow.getSlides();

            for (int i = 0, row = slideList.size(); i < row; i++) {
                //获取每一页幻灯片
                XSLFSlide slide = slideList.get(i);

                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("宋体");
                            }
                        }
                    }
                }


                //根据幻灯片尺寸创建图形对象
                BufferedImage bufferedImage = new BufferedImage((int)dimension.getWidth(), (int)dimension.getHeight(), BufferedImage.TYPE_INT_RGB);

                Graphics2D graphics2d = bufferedImage.createGraphics();

                graphics2d.setPaint(Color.white);
                graphics2d.setFont(new java.awt.Font("宋体", java.awt.Font.PLAIN, 12));

                //把内容写入图形对象
                slide.draw(graphics2d);

                graphics2d.dispose();

                //封装到Image对象中
                Image image = Image.getInstance(bufferedImage, null);
                image.scalePercent(50f);

                // 写入单元格
                pdfPTable.addCell(new PdfPCell(image, true));
                document.add(image);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (document != null) {
                    document.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
                if (pdfWriter != null) {
                    pdfWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }


    public static boolean pptToPdf(String pptPath, String pdfDir) {

        if (StringUtils.isEmpty(pptPath)) {
            throw new RuntimeException("word文档路径不能为空");
        }

        if (StringUtils.isEmpty(pdfDir)) {
            throw new RuntimeException("pdf目录不能为空");
        }


        String pdfPath = pdfDir + "te." + "pdf";

        Document document = null;
        HSLFSlideShow hslfSlideShow = null;
        FileOutputStream fileOutputStream = null;
        PdfWriter pdfWriter = null;

        try {
            //使用输入流ppt文件
            hslfSlideShow = new HSLFSlideShow(new FileInputStream(pptPath));

            // 获取ppt文件页面
            Dimension dimension = hslfSlideShow.getPageSize();

            fileOutputStream = new FileOutputStream(pdfPath);

            document = new Document();

            // pdfWriter实例
            pdfWriter = PdfWriter.getInstance(document, fileOutputStream);

            document.open();

            PdfPTable pdfPTable = new PdfPTable(1);

            List<HSLFSlide> hslfSlideList = hslfSlideShow.getSlides();

            for (int i=0; i < hslfSlideList.size(); i++) {
                HSLFSlide hslfSlide = hslfSlideList.get(i);

                for (HSLFShape shape : hslfSlide.getShapes()) {

                    if (shape instanceof HSLFTextShape){
                        // 设置字体, 解决中文乱码
                        HSLFTextShape textShape = (HSLFTextShape) shape;

                        for (HSLFTextParagraph textParagraph : textShape.getTextParagraphs()) {
                            for (HSLFTextRun textRun : textParagraph.getTextRuns()) {
                                textRun.setFontFamily("宋体");
                            }
                        }
                    }

                }
                BufferedImage bufferedImage = new BufferedImage((int)dimension.getWidth(), (int)dimension.getHeight(), BufferedImage.TYPE_INT_RGB);

                Graphics2D graphics2d = bufferedImage.createGraphics();

                graphics2d.setPaint(Color.white);
                graphics2d.setFont(new java.awt.Font("宋体", java.awt.Font.PLAIN, 12));

                hslfSlide.draw(graphics2d);

                graphics2d.dispose();

                Image image = Image.getInstance(bufferedImage, null);
                image.scalePercent(50f);

                // 写入单元格
                pdfPTable.addCell(new PdfPCell(image, true));
                document.add(image);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (document != null) {
                    document.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
                if (pdfWriter != null) {
                    pdfWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }


    public static void main(String[] args) {
        boolean successful = false;
        // ppt to pdf
        successful = pptxToPdf("D:\\test1.pptx", "D:\\");

        // pptx to pdf
        //	 successful = PdfConvertUtil.pptxToPdf("D:\\360_js\\测321pt.pptx", "D:\\360_js");

        System.out.println("转换" + (successful ? "成功" : "失败"));
    }

}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Abner G

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值