Jodconverter的版本:jodconverter 2.2.1
maven:
- <dependency>
- <groupId>com.artofsolving</groupId>
- <artifactId>jodconverter</artifactId>
- <version>2.2.1</version>
- </dependency>
网上的流传的方法:
1. 安装OpenOffice 3 下载路径:http://zh.openoffice.org/new/zh_cn/downloads.html
2. 启动OpenOffice服务
cd C:\Program Files\OpenOffice.org 3\program
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
3. 利用Jodconverter编写转换类
- public void convert(String input, String output){
- File inputFile = new File(input);
- File outputFile = new File(output);
- OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
- try {
- connection.connect();
- DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
- converter.convert(inputFile, outputFile);
- } catch(Exception e) {
- e.printStackTrace();
- } finally {
- try{ if(connection != null){connection.disconnect(); connection = null;}}catch(Exception e){}
- }
- }
以上方法需要启动OpenOffice的服务,麻烦且占内存。
后来,有人又整理了一个方法:直接在转换类中调用启动服务。
- public static int office2PDF(String sourceFile, String destFile) {
- String OpenOffice_HOME = "D:/Program Files/OpenOffice.org 3";// 这里是OpenOffice的安装目录,
- // 在我的项目中,为了便于拓展接口,没有直接写成这个样子,但是这样是尽对没题目的
- // 假如从文件中读取的URL地址最后一个字符不是 '\',则添加'\'
- if (OpenOffice_HOME.charAt(OpenOffice_HOME.length() - 1) != '/') {
- OpenOffice_HOME += "/";
- }
- Process pro = null;
- try {
- // 启动OpenOffice的服务
- String command = OpenOffice_HOME
- + "program/soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";
- pro = Runtime.getRuntime().exec(command);
- // connect to an OpenOffice.org instance running on port 8100
- OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);
- connection.connect();
- // convert
- DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
- converter.convert(inputFile, outputFile);
- // close the connection
- connection.disconnect();
- // 封闭OpenOffice服务的进程
- pro.destroy();
- return 0;
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- return -1;
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- pro.destroy();
- }
- return 1;
- }