LibreOffice 转成pdf与html格式,实现在线预览

試著忘記壹切 提交于 2020-08-07 13:30:37
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 sourceFileName = sourceFileRelativePath.substring(sourceFileRelativePath.lastIndexOf("\\")+1);
        //预览文件的相对目录
        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));
        }
        return targetDir + sourceFileName;
    }
    
    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;  
        } 
    }
    
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!