使用Libreoffice处理office文档,OFFICE转PDF,OFFICE转图片,OFFICE转图片包含加水印逻辑

主要逻辑为office转pdf

office转图片实际上是先转为pdf再利用另外一个工具类转为图片

转图片工具类请看另一篇文章

import org.apache.commons.lang3.StringUtils;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.annotation.PostConstruct;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Pattern;

/**
 * OfficeOperatingUtil 说明: word文件转换成pdf文件(必须安装Openoffice或LiberOffice)
 */
public class OfficeOperatingUtil {

    static OfficeManager officeManager;

    private static ReentrantLock OfficeLock = new ReentrantLock();

    @PostConstruct
    public void init() {
        DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();
        // 设置LibreOffice的安装目录
        config.setOfficeHome(getOfficeHome());
        // 启动LibreOffice的服务
        OfficeManager getOfficeManager = config.buildOfficeManager();
        if (getOfficeManager == null) {
            getOfficeManager.start();
        }
        officeManager = getOfficeManager;
    }

    private static Logger logger = LoggerFactory.getLogger(OfficeOperatingUtil.class);

    /**
     * 锁
     */
    private static Lock lock = new ReentrantLock();

    /**
     * windows下openoffice或LiberOffice安装地址
     */
    private static String windowsOpenOfficeUrl = "C:\\Program Files\\LibreOffice";
    /**
     * linux下openoffice或LiberOffice安装地址
     */
    private static String linuxOpenOfficeUrl = "/opt/libreoffice6";
    /**
     * mac下opneoffice安装地址
     */
    private static String macOpenofficeUrl = "/Applications/OpenOffice.org.app/Contents/";

    /**
     * 使Office2003-2007全部格式的文档(.doc|.docx|.xls|.xlsx|.ppt|.pptx) 转化为pdf文件 无加水印逻辑
     * 
     * @param inputFilePath  输入文件路径
     * @param outputFilePath 输出文件路径
     * @return 返回转换后文件路径
     * @throws Exception
     */
    public static String officeToPdf(String inputFilePath, String outputFilePath) throws Exception {
        try {
            if (officeManager == null) {
                // 如果LibreOffice中途关闭了 再次启动 防止报错
                officeManager = getOfficeManager();
            }
            if (StringUtils.isEmpty(inputFilePath)) {
                logger.info("输入文件地址为空,转换终止!");
                return null;
            }
            File inputFile = new File(inputFilePath);
            // 转换后的pdf文件
            File outputFile = new File(outputFilePath);
            if (!inputFile.exists()) {
                logger.info("输入文件不存在,转换终止!");
                return null;
            }
            // 连接LibreOffice
            OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
            return converterFile(inputFile, outputFilePath, inputFilePath, converter);
        } catch (Exception e) {
            logger.error("word转化pdf出错!", e);
            throw e;
        }
    }

    /**
     * office转图片,加水印,如果不传则不加,两个水印参数都有则取图片
     * 
     * @param inputFilePath    office文件路径
     * @param strWatermark     文字水印
     * @param imgWatermarkPath 图片水印图片的路径
     * @param pageList         水印添加的页码(传空则全部页码添加水印)
     * @return
     */
    public static List<String> officeToImg(String inputFilePath, String strWatermark, String imgWatermarkPath,
            ArrayList<String> pageList) {
        try {
            // word转成pdf
            String tempOutputFilePath = getTempOutputFilePath(inputFilePath);
            String tempPdfFilePath = officeToPdf(inputFilePath, tempOutputFilePath);
            // pdf加水印
            String waterPdfPath = tempPdfFilePath;
            if (StringUtils.isNotEmpty(imgWatermarkPath)) {
                waterPdfPath = getOutputFilePath(inputFilePath);
                if (!WatermarkUtil.setImgWatermark2PDFByPage(inputFilePath, waterPdfPath, imgWatermarkPath, pageList)) {
                    waterPdfPath = tempPdfFilePath;// 添加失败
                }
            } else {
                if (StringUtils.isNotEmpty(strWatermark)) {
                    waterPdfPath = getOutputFilePath(inputFilePath);
                    if (!WatermarkUtil.setStrWatermark2PDFByPage(inputFilePath, waterPdfPath, strWatermark, pageList)) {
                        waterPdfPath = tempPdfFilePath;// 添加失败
                    }
                }
            }
            // pdf转图片
            List<String> iamgeFilePath = PdfToImageUtil.pdfToIamge(waterPdfPath);
            for (String string : iamgeFilePath) {
                logger.info("图片地址:" + string);
            }
            // 删除pdf文件
            new File(tempPdfFilePath).delete();
            new File(waterPdfPath).delete();
            return iamgeFilePath;
        } catch (Exception e) {
            logger.error("word转化图片出错!", e);
            return null;
        }
    }

    /**
     * 获取输出pdf文件路径,如:"e:/test.doc"返回"e:/test.pdf"
     *
     * @param inputFilePath
     * @return
     */
    public static String getOutputFilePath(String inputFilePath) {
        String outputFilePath = inputFilePath.replaceAll("." + getPostfix(inputFilePath), ".pdf");
        return outputFilePath;
    }

    /**
     * 获取临时PDF输出文件路径,如:"e:/test.doc"返回"e:/testtemp.pdf"
     *
     * @param inputFilePath
     * @return
     */
    public static String getTempOutputFilePath(String inputFilePath) {
        String outputFilePath = inputFilePath.replaceAll("." + getPostfix(inputFilePath), "temp.pdf");
        return outputFilePath;
    }

    /**
     * 获取inputFilePath的后缀名,如:"e:/test.pptx"的后缀名为:"pptx"
     * 
     * @param inputFilePath
     * @return
     */
    public static String getPostfix(String inputFilePath) {
        return inputFilePath.substring(inputFilePath.lastIndexOf(".") + 1);
    }

    /**
     * 连接LibreOffice.org 并且启动LibreOffice.org
     * 
     * @return
     */
    public static OfficeManager getOfficeManager() {
        DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();
        // 设置LibreOffice.org 3的安装目录
        config.setOfficeHome(getOfficeHome());
        // 端口号
        config.setPortNumber(8100);
        config.setTaskExecutionTimeout(1000 * 60 * 25L);
//         设置任务执行超时为10分钟
        config.setTaskQueueTimeout(1000 * 60 * 60 * 24L);
//         设置任务队列超时为24小时
        // 启动LibreOffice的服务
        OfficeManager getOfficeManager = config.buildOfficeManager();
        getOfficeManager.start();
        return getOfficeManager;
    }

    /**
     * 根据操作系统的名称,获取LibreOffice.org 3的安装目录<br>
     * 如我的LibreOffice.org 3安装在:C:/Program Files (x86)/LibreOffice.org 3<br>
     * 
     * @return LibreOffice.org 3的安装目录
     */
    public static String getOfficeHome() {
        String osName = System.getProperty("os.name");
        logger.info("操作系统名称:" + osName);
        if (Pattern.matches("Linux.*", osName)) {
            return linuxOpenOfficeUrl;
        } else if (Pattern.matches("Windows.*", osName)) {
            return windowsOpenOfficeUrl;
        } else if (Pattern.matches("Mac.*", osName)) {
            return macOpenofficeUrl;
        }
        return null;
    }

    /**
     * 文件转换方法
     * 
     * @param inputFile          输入文件
     * @param outputFilePath_end 输出文件路径
     * @param inputFilePath      输入文件路径
     * @param converter          转换器对象
     * @return
     * @throws Exception
     */
    public static String converterFile(File inputFile, String outputFilePath_end, String inputFilePath,
            OfficeDocumentConverter converter) throws Exception {
        File outputFile = new File(outputFilePath_end);
        // 假如目标路径不存在,则新建该路径
        if (!outputFile.getParentFile().exists()) {
            outputFile.getParentFile().mkdirs();
        }
        // 判断转换文件的编码方式,如果不是UTF-8,则改为UTF-8编码
        converter.convert(inputFile, outputFile);
        logger.info("文件:" + inputFilePath + "\n转换为\n目标文件:" + outputFile + "\n成功!");
        if (outputFile.isFile() && outputFile.exists()) {
            return outputFilePath_end;
        } else {
            throw new Exception("转换的目标文件不存在 路径" + outputFilePath_end);
        }
    }

    public void setLinuxOpenOfficeUrl(String linuxOpenOfficeUrl) {
        OfficeOperatingUtil.linuxOpenOfficeUrl = linuxOpenOfficeUrl;
    }

    public void setWindowsOpenOfficeUrl(String windowsOpenOfficeUrl) {
        OfficeOperatingUtil.windowsOpenOfficeUrl = windowsOpenOfficeUrl;
    }

}

 

posted @ 2019-01-23 15:40  RivenLw  阅读(2338)  评论(0编辑  收藏  举报