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

摘要:
“);returnnull;}FileinputFile=newFile;//转换后的pdf文件FileoutputFile=newFile;如果(!InputFile.exists()){logger.info(”输入文件不存在,转换终止!

主要逻辑为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 + "
转换为
目标文件:" + outputFile + "
成功!");
        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;
    }

}

免责声明:文章转载自《使用Libreoffice处理office文档,OFFICE转PDF,OFFICE转图片,OFFICE转图片包含加水印逻辑》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Java实现 蓝桥杯 历届试题 最大子阵WindowsService实现邮件定时发送下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

利用Servlet在客户端输出PDF文件

  在学习编程的过程中,我觉得不止要获得课本的知识,更多的是通过学习技术知识提高解决问题的能力,这样我们才能走在最前方,本文主要讲述利用Servlet在客户端输出PDF文件,更多Java专业知识,广州疯狂java培训为你讲解;   首先,要在客户端输出PDF文件,必须将HTTP的请求头的MIME进行设置。   response.setContentType...

Unity3d在Android环境下读取XML的注意事项

PC环境下读取一般可以直接用 XmlDocument doc = new XmlDocument(); doc.Load(path);可以直接加载进来。 path为直接路径。 此时路径可以为streamingAssets文件夹下,也可以是自己自建的文件夹下面,如果是你自己建的文件夹下打包后需要手动添加一下,就是说比如你自己在Assets文件下新建了一个Co...

SpringCloud入门之常用的配置文件 application.yml和 bootstrap.yml区别

SpringBoot默认支持properties和YAML两种格式的配置文件。前者格式简单,但是只支持键值对。如果需要表达列表,最好使用YAML格式。SpringBoot支持自动加载约定名称的配置文件,例如application.yml。如果是自定义名称的配置文件,就要另找方法了。可惜的是,不像前者有@PropertySource这样方便的加载方式,后者的...

轻松玩转AI 与PDF文件的转化(完美解决字体问题)

经过漫长而坚苦卓绝的研究查阅了网上无数资料下载了众多相关软件进行试验终于,找到搞定PDF文件的方便并且有效的办法PDF文件!你这个魔鬼!退去吧!!!!难点一: 如何修改客户常常会提供不知道从哪里搞来的PDF文件然后要求修改上面的某个细节听上去很简单,但是真正捣鼓起来你会发现传说中的 Adobe Acrobat只能完成页面的增减,标签的添加,甚至可以做到添加...

微信内 H5 页面自定义分享

起源: 最近公司在做一个活动的h5页面,在微信内打开时需要进行微信授权,然后后端会重定向到这个页面并且携带了一些参数(openid等)。问题是点击微信的原生分享时,会把携带的这些参数一起分享出去,等于把用户信息泄露了。所以为了解决这个问题,只能实现自定义微信分享的功能,可以自定义分享的地址、标题、图标还有简介。 事先需要做的: 1.微信公众号:必须是经过...

ZYNQ:使用PetaLinux打包 BOOT.BIN、image.ub

说明 个人还是比较喜欢灵活去管理各个部分的源码。 有关文章:ZYNQ:PetaLinux提取Linux和UBoot配置、源码 编译Linux 取得Linux源代码和配置后,可以在其中执行make,编译Linux。 注意,编译前请导入PetaLinux环境变量: 设置和导出ARCH为arm或者arm64; 设置和导出CROSS_COMPILE,比如aar...