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

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;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值