欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JAVA --Office文件转换为PPT及PPT文件转换成图片 --支持.docx .xlsx .pptx (使用OpenOffice)

程序员文章站 2024-01-21 19:54:22
...

JAVA --Office文件转换为PPT及PPT文件转换成图片 --支持.docx .xlsx .pptx 使用OpenOffice


第二更,开发项目的时候遇到很这个需求,要把word、excel、ppt转换成图片,我也是借鉴了很多前辈的代码,亲测可用。一来分享给大家,二来我自己的记性也不太好,需要的时候留给自己翻看。废话不多说,直接上代码。

Maven依赖

		   <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.4</version>
        </dependency>
        <dependency>
            <groupId>com.artofsolving</groupId>
            <artifactId>jodconverter</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.openoffice</groupId>
            <artifactId>juh</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.openoffice</groupId>
            <artifactId>jurt</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.openoffice</groupId>
            <artifactId>ridl</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.openoffice</groupId>
            <artifactId>unoil</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.1</version>
        </dependency>

我是在springboot环境下搭建的,这里的 jodconverter maven*仓库最高版本是2.2.1,好像对office2017版的支持不太好,我找了很久找到了2.2.2版本的,这里也分享给大家,当然你也可以把版本写改成2.2.1

链接:https://pan.baidu.com/s/1jjyL5w90qsNWpWrgTbOFRg
提取码:pmvt

然后把下载的jar包安装到本地maven仓库中,windows下cmd运行下面的命令

mvn install:install-file -Dfile=${filePath} -DgroupId=com.artofsolving -DartifactId=jodconverter -Dversion=2.2.2 -Dpackaging=jar

其中‘filePath‘为jar包所在路径

下载 Apache_OpenOffice_4.1.2并安装

本来想去官网下载的,无奈网络太烂了,只能网上随便找了个版本,安装一路下一步,我是安装到了C:\Program Files (x86)\OpenOffice 4下。当然linux环境也有安装包。

唯一Id生成器

传说中的雪花算法生成器,本人不太喜欢用UUID,感觉这个用起来不错,粘过去直接用吧(我也看不太懂)

import org.springframework.stereotype.Component;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;

@Component
public class IdWorker {

    private final static long twepoch = 1288834974657L;

    private final static long workerIdBits = 5L;

    private final static long datacenterIdBits = 5L;

    private final static long maxWorkerId = -1L ^ (-1L << workerIdBits);

    private final static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);

    private final static long sequenceBits = 12L;

    private final static long workerIdShift = sequenceBits;

    private final static long datacenterIdShift = sequenceBits + workerIdBits;

    private final static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;

    private final static long sequenceMask = -1L ^ (-1L << sequenceBits);

    private static long lastTimestamp = -1L;

    private long sequence = 0L;

    private final long workerId;
    // 数据标识id部分
    private final long datacenterId;

    public IdWorker(){
        this.datacenterId = getDatacenterId(maxDatacenterId);
        this.workerId = getMaxWorkerId(datacenterId, maxWorkerId);
    }

    public IdWorker(long workerId, long datacenterId) {
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    public synchronized long nextId() {
        long timestamp = timeGen();
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }

        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }
        lastTimestamp = timestamp;
        long nextId = ((timestamp - twepoch) << timestampLeftShift)
                | (datacenterId << datacenterIdShift)
                | (workerId << workerIdShift) | sequence;

        return nextId;
    }

    private long tilNextMillis(final long lastTimestamp) {
        long timestamp = this.timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = this.timeGen();
        }
        return timestamp;
    }

    private long timeGen() {
        return System.currentTimeMillis();
    }

    protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) {
        StringBuffer mpid = new StringBuffer();
        mpid.append(datacenterId);
        String name = ManagementFactory.getRuntimeMXBean().getName();
        if (!name.isEmpty()) {

            mpid.append(name.split("@")[0]);
        }

        return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1);
    }

    protected static long getDatacenterId(long maxDatacenterId) {
        long id = 0L;
        try {
            InetAddress ip = InetAddress.getLocalHost();
            NetworkInterface network = NetworkInterface.getByInetAddress(ip);
            if (network == null) {
                id = 1L;
            } else {
                byte[] mac = network.getHardwareAddress();
                id = ((0x000000FF & (long) mac[mac.length - 1])
                        | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
                id = id % (maxDatacenterId + 1);
            }
        } catch (Exception e) {
            System.out.println(" getDatacenterId: " + e.getMessage());
        }
        return id;
    }
}

转换类

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.vergil.officedemo.utils.IdWorker;
import org.apache.commons.io.FileUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

@Component
public class TransformOffice2Image {
    //唯一Id生成工具
    private final IdWorker idWorker;

    //日志打印,由于是非阻塞的,性能比<code>System.out.println();</code>要好
    private static final Logger logger = LoggerFactory.getLogger(TransformOffice2Image.class);

    @Autowired
    public TransformOffice2Image(IdWorker idWorker) {
        this.idWorker = idWorker;
    }

    /**
     * 将office文件转换为pdf文件
     *
     * @param officePath office文件的路径,参数的非空校验我就不做了
     * @param dirPath    文件存放位置
     * @return 生成的pdf文件路径
     */
    public String transformOffice2Pdf(String officePath, String dirPath) {
        //创建一个唯一的临时文件夹来存放生成的文件
        String tempDirPath = dirPath + "/" + idWorker.nextId() + "/";
        String pdfPath = null;
        Process process = null;
        OpenOfficeConnection connection = null;
        try {
            //强制创建文件夹,apache的io-commons工具类就是好用
            FileUtils.forceMkdir(new File(tempDirPath));
            pdfPath = tempDirPath + idWorker.nextId() + ".pdf";
            //soffice.exe为OpenOffice的执行文件,端口8100最好不要改
            String command = "C:/Program Files (x86)/OpenOffice 4/program/soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";
            //执行这条命令,相当于在Windows的cmd里面执行
            process = Runtime.getRuntime().exec(command);
            connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);
            //建立连接
            connection.connect();
            DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
            //开始转换
            converter.convert(new File(officePath), new File(pdfPath));
        } catch (IOException e) {
            logger.error("Office转换异常", e);
        } finally {
            //最后别忘了关连接
            connection.disconnect();
            process.destroy();
        }
        return pdfPath;
    }

    /**
     * @param pdfPath pdf文件路径
     * @param dirPath 生成的图片存放路径
     */
    public void transformPdf2Image(String pdfPath, String dirPath) {
        // 创建一个唯一的临时文件夹来存放生成的文件
        String tempDirPath = dirPath + "/" + idWorker.nextId() + "/";
        PDDocument document = null;
        try {
            FileUtils.forceMkdir(new File(tempDirPath));
            //加载Pdf文件
            document= PDDocument.load(new File(pdfPath));
            PDFRenderer renderer = new PDFRenderer(document);
            if (document != null) {
                PDPageTree pages = document.getPages();
                int startPage = 0;
                int len = pages.getCount();
                if (startPage < len) {
                    for (int i = startPage; i < len; i++) {
                        StringBuilder sb = new StringBuilder();
                        //按照页码生成图片名
                        sb.append(tempDirPath).append("page-").append(i + 1).append(".png");
                        String imagePath = sb.toString();
                        BufferedImage image = renderer.renderImage(i);
                        ImageIO.write(image, "png", new File(imagePath));
                    }
                }
            }
        } catch (IOException e) {
           logger.error("转换PDF异常",e);
        } finally {
            try {
                //最后别忘了关文档
                document.close();
            } catch (IOException e) {
                logger.error("关闭PDF异常",e);
            }
        }
    }
}

有什么疑问可以加我qq:540814390,大家一起来交流。