利用libreoffice转pdf

下载libreoffice,并安装

public class LibreOffice2PdfUtils {

private static Logger logger = LoggerFactory.getLogger(LibreOffice2PdfUtils.class);
/**
* 获取当前操作系统名称. return 操作系统名称 例如:windows,Linux,Unix等.
*/
public static String getOSName() {
/*
* String osName = System.getProperty("os.name").toLowerCase(); PropertiesLoader
* propertiesLoader = new PropertiesLoader(); if (Pattern.matches("Linux.*",
* osName)) { return propertiesLoader.getProperty("libreOfficeUrl"); } else if
* (Pattern.matches("Windows.*", osName)) { return
* propertiesLoader.getProperty("libreOfficeUrl"); } return null;
*/
return Global.getConfig("libreOfficeUrl");
}

public static String libreOffice2PDF(String sourceFile) {


logger.info("文档转pdf:");
logger.info("输入的文档URL"+sourceFile);
File inputFile = new File(Global.getConfig("userfiles.basedir") + sourceFile);
if (!inputFile.exists()) {
logger.info("文件不存在");
return null;// 文件不存在
}
String newPath = sourceFile.substring(0, sourceFile.indexOf("."));
String OpenOffice_HOME = getOSName();
String basePath = Global.getConfig("userfiles.basedir") + "/userfiles/";
String filePath = DateUtils.getDate();
String path = basePath + filePath;
String newFileName =  newPath + ".pdf";
// 启动OpenOffice的服务
String command = OpenOffice_HOME + " --headless --convert-to pdf --outdir " + path + " " + inputFile.getAbsolutePath();
System.out.println("command:" + command);
Process pro = null;
try {
pro = Runtime.getRuntime().exec(command);
InputStream in = pro.getErrorStream();
while (in.read() != -1) {
System.out.println(in.read());
logger.info("转换成功");
}
in.close();
} catch (IOException e) {
logger.info("转换失败");
e.printStackTrace();
return null;
} finally {
if (pro != null) {
pro.destroy();
}
}
logger.info("新的文件路径"+newFileName);
return newFileName;
}

/*public static void main(String[] args) {
String s="D:/home/tomcat8080/webapps/userfiles/2018-05-08/bbb.doc";
libreOffice2PDF(s);
}*/
}

猜你喜欢

转载自blog.csdn.net/baopeng1993/article/details/81014663