windows/linux服务器上java使用openoffice将word文档转换为PDF(亲测可用)

一、  前言
1. 开发过程中经常会使用java将office系列文档转换为PDF, 一般都使用微软提供的openoffice+jodconverter 实现转换文档。
2. openoffice既有windows版本也有linux版。不用担心生产环境是linux系统。
二、 准备
1. 下载安装openoffice   http://www.openoffice.org/  (路径随意,因为不管怎么选路径,咱们想要的都在"C:/Program Files (x86)/OpenOffice 4/",版本建议选最新的)
2. 安装完事后 cmd  运行  cd C:\Program Files\OpenOffice.org 3\program>soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard (Linux上自己百度,太多了)
3. 准备jar包(下面这些基本上够了,至于报错你就在根据报错的提示下载吧!)
commons-cli-1.0.jar
commons-io-1.3.1.jar
jodconverter-2.2.1.jar
jodconverter-cli-2.2.1.jar
juh-2.3.0.jar
jurt-2.3.0.jar
ridl-2.3.0.jar
slf4j-api-1.4.3.jar
slf4j-jdk14-1.4.3.jar
unoil-2.3.0.jar
xstream-1.2.2.jar
三、 干活
1. 主要部分
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

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 WordToPdf {
    public static int office2PDF(String sourceFile, String destFile) {
        //String OpenOffice_HOME = "D:/Program Files/OpenOffice.org 3";// 这里是OpenOffice的安装目录,C:\Program Files (x86)\OpenOffice 4
          String OpenOffice_HOME = "C:/Program Files (x86)/OpenOffice 4/";
        // 在我的项目中,为了便于拓展接口,没有直接写成这个样子,但是这样是尽对没题目的
        // 假如从文件中读取的URL地址最后一个字符不是 '\',则添加'\'
        if (OpenOffice_HOME.charAt(OpenOffice_HOME.length() - 1) != '/') {
            OpenOffice_HOME += "/";
        }
        Process pro = null;

        try {
            File inputFile = new File(sourceFile);
            if (!inputFile.exists()) {
                return -1;// 找不到源文件, 则返回-1
            }
            // 如果目标路径不存在, 则新建该路径
            File outputFile = new File(destFile);
            if (!outputFile.getParentFile().exists()) {
                outputFile.getParentFile().mkdirs();
            }
            // 启动OpenOffice的服务
            String command = OpenOffice_HOME  
                    + "program\\soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;StarOffice.ServiceManager\" -nofirststartwizard"; 
            pro = Runtime.getRuntime().exec(command);
            // connect to an OpenOffice.org instance running on port 8100
            OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);
            //OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
            connection.connect();

            // convert
            DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
            converter.convert(inputFile, outputFile);
            //converter.convert(inputFile,xml,outputFile,pdf);

            // 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;
    }


    public static void main(String[] args){
       // WordToPdf wordToPdf = new WordToPdf();
       
    }

}
2.  测试部分
public static void main(String[]args) throws Exception{
        String sourceFile = "E:\\zgtzs.doc";
        String destFile = "E:\\pdfdest.pdf";
        int i =  WordToPdf.office2PDF(sourceFile, destFile);
        System.out.println(i);
}

 

10月12日新增
上面的word转pdf只限正规的word转(如果你的Word是通过freemark等xml模板转过来的,那你转成pdf后是一对xml代码,建议你用poi转代码如下)
1.所需jar包

  dom4j-1.6.1.jar
  poi-3.12-20150511.jar
  poi-examples-3.12-20150511.jar
  poi-excelant-3.12-20150511.jar
  poi-ooxml-3.12-20150511.jar
  poi-ooxml-schemas-3.12-20150511.jar
  poi-scratchpad-3.12-20150511.jar
  xmlbeans-2.3.0.jar

2. 代码
  
       public void testWrite() throws Exception {  
          String templatePath = "E:\\demo\\zgtzs.doc";  //这个是一个doc模板   样式完全不会乱
          InputStream is = new FileInputStream(templatePath);  
          HWPFDocument doc = new HWPFDocument(is);  
          Range range = doc.getRange();  
          //替换数据(当然如果你要替换的比较多,那建议你写一个实体类的反射来填充数据)
          range.replaceText("${top_year}", new SimpleDateFormat("yyyy").format(new Date()));  
          range.replaceText("${content_year1}", new SimpleDateFormat("yyyy").format(new Date()));  
          range.replaceText("${unit}", "北京云盾科技666");  
          range.replaceText("${bianHao}", "22");  
          range.replaceText("${content2}", "asdfasdfasdfassdfasdfasdfaf");  
          OutputStream os = new FileOutputStream("E:\\demo\\write2.doc");  
          //把doc输出到输出流中  
          doc.write(os);  
          os.close();
          is.close();
       }

3. 至于模板我还是截个图吧!

posted on 2017-10-10 16:58  w强哥  阅读(7423)  评论(0编辑  收藏  举报

导航