importjava.io.File;importjava.io.IOException;importjava.io.InputStream;importorg.apache.commons.io.IOUtils;importorg.apache.commons.lang3.StringUtils;public classLibreOfficeUtil {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) throwsIOException {
System.out.println(convert("a.docx", "pdf"));
}/***@paramsourceFilePath 源文件地址
*@paramtargetDir 目标文件目录
*@paramtargetType 目标文件类型
*@throwsIOException*/
public static String convert(String sourceFileRelativePath, String targetType) throwsIOException {
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 newRuntimeException(IOUtils.toString(errorStream, ENCODEING_UTF8));
}return targetDir +sourceFileName;
}public static voidcreateDir(String dirPath) {
File fd= null;try{
fd= newFile(dirPath);if (!fd.exists()) {
fd.mkdirs();
}
}catch(Exception e) {
e.printStackTrace();
}finally{
fd= null;
}
}
}