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; } } }
看完打开支付宝扫一扫领个红包吧!