LibreOffice 轉成pdf與html格式,實現在線預覽


import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

public class LibreOfficeUtil {
    
    private static final String LIBER_OFFICE_HOME = "C:/Program Files/LibreOffice/program/";
    private static final String FILE_DOWNLOAD_PATH = "d:/test/file/";
    private static final String FILE_PREVIEW_PATH = "d:/test/preview/";
    private static final String ENCODEING_UTF8 = "UTF-8";
    
    
    public static void main(String[] args) throws IOException {
        System.out.println(convert("a.docx", "pdf"));
    }

    /**
     * @param sourceFilePath 源文件地址
     * @param targetDir 目標文件目錄
     * @param targetType 目標文件類型
     * @throws IOException
     */
    public static String convert(String sourceFileRelativePath, String targetType) throws IOException {
        //預覽文件的相對目錄
        String targetDir = DateTimeUtil.getCurrentShortDateStr() + "/" + String.valueOf(System.currentTimeMillis()) + "/";
        String previewAbsolutelyDir = FILE_PREVIEW_PATH + targetDir;
        
        StringBuffer command = new StringBuffer(LIBER_OFFICE_HOME).append("soffice --headless --invisible --convert-to ")
                .append(targetType).append(" --language=").append(ENCODEING_UTF8).append(" ")
                .append(FILE_DOWNLOAD_PATH).append(sourceFileRelativePath).append(" --outdir ")
                .append(previewAbsolutelyDir);
        //創建目錄--因為目錄不一定不存在
        createDir(previewAbsolutelyDir);
        //返回過程對象--Process
        Process exec = Runtime.getRuntime().exec(command.toString());
        //結果信息
        InputStream inputStream = exec.getInputStream();
        //IOUtils-直接將流轉化成字符串
        String result = IOUtils.toString(inputStream, ENCODEING_UTF8);
        if(StringUtils.isBlank(result)) {
            //錯誤信息
            InputStream errorStream = exec.getErrorStream();
            throw new RuntimeException(IOUtils.toString(errorStream, ENCODEING_UTF8));
        }
        String sourceFileName = sourceFileRelativePath.substring(sourceFileRelativePath.lastIndexOf("\\") + 1).substring(0, sourceFileRelativePath.lastIndexOf(".")+1);
        return targetDir + sourceFileName + targetType;
    }
    
    public static void createDir(String dirPath) {
        File fd = null;  
        try {  
            fd = new File(dirPath);  
            if (!fd.exists()) {  
                fd.mkdirs();  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            fd = null;  
        } 
    }
    
}

 


免責聲明!

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



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