openoffice java实现word转PDF

来源:互联网 发布:java html转义 编辑:程序博客网 时间:2024/05/16 12:42

看了网上好多实现word转PDF的文章,都是源码能找到,找不到所依赖的jar包 ,发表一个有jar包的demo.

附带下载openoffice的下载地址:http://www.openoffice.org/


package office2PDF;



import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.ConnectException;
import java.util.Date;


import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;


public class office2PDF {


public static void main(String[] args) {

Date startDate = new Date();  
        String sourceFile = "C:\\Users\\Ice\\Desktop\\aaa.doc";  
        String destFile = "C:\\Users\\Ice\\Desktop\\zrc.pdf";  
        try {
System.out.println(office2PDF(sourceFile, destFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}  
        Date endDate = new Date();  
        System.out.println("the cost time is "+(endDate.getTime()-startDate.getTime()));  

}


public static int office2PDF(String sourceFile, String destFile) throws FileNotFoundException {  
        try {  
            File inputFile = new File(sourceFile);  
            if (!inputFile.exists()) {  
                return -1;// 找不到源文件, 则返回-1  
            }  
  
            // 如果目标路径不存在, 则新建该路径  
            File outputFile = new File(destFile);  
            if (!outputFile.getParentFile().exists()) {  
                outputFile.getParentFile().mkdirs();  
            }  
              
            // 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();  
  
            return 0;  
        } catch (ConnectException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
  
        return 1;  
    } 

}
原创粉丝点击