使用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;
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM