分享

openOffice 转换文件格式

 WindySky 2016-09-20

       引言:突然接到任务,要将word或者ppt转换成HTML的格式在页面上显示,类似于百度文库的效果。以前也听说过,觉得用java实现起来还是很简单的。于是我就带着我的任务以及我的好奇心出发了,在网上找了些资料,最终决定用OpenOffice。

  首先简单的介绍下转换需要的环境:

     1、转换组要安装openoffice软件(下载地址:http://download./index.html

     2、需要下载jodconverter包

  在此我提供了jodconverter包(包括jodconverter2、jodconverter3,注:jodconverter2需要手动启动openoffice服务,如有不清楚的地方可以在我文章下面留言),下载请点击...

      JODConverter是一个开源文档转换工具,既可以应用于Linux平台,也可其应用于Windows平台。其基于OpenOffice.org或者LibreOffice。因此,文档转换服务器上必须安装有OpenOffice或者LibreOffice。

  目前最新版本的JODConverter为JODConverter3.0,它要求JDK1.5以上的Java环境,同时还需要OpenOffice.org 3.x版本。本文基于最新版本3.0设计实现,如果是版本为2,则有不同的实现。(版本2需要手动启动OpenOffice.org服务,或者创建Windows服务设置为开机启动,而版本3提供了开启服务的接口,在此我使用的是版本3)

   一切准备就绪那就直接开始了...

 下面是一个比较完整的例子,可以实现 WORD==>HTML 、PPT==>HTML、WORD==>PDF、PPT==>PDF的转换。

  1. package core;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.FileNotFoundException;  
  7. import java.io.IOException;  
  8. import java.io.InputStreamReader;  
  9. import java.util.Date;  
  10. import java.util.regex.Matcher;  
  11. import java.util.regex.Pattern;  
  12.   
  13. import org.artofsolving.jodconverter.OfficeDocumentConverter;  
  14. import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;  
  15. import org.artofsolving.jodconverter.office.OfficeManager;  
  16.   
  17. //转换文档为pdf  
  18. public class OpenOfficePdfConvert {  
  19.   
  20.     /** 
  21.      * @param args 
  22.      */  
  23.     private static OfficeManager officeManager;  
  24.     private static String OFFICE_HOME = "d:\\Program Files\\OpenOffice.org 3";// 安装OPenOffice  
  25.     // 的路径  
  26.     private static int port[] = { 8100 };  
  27.   
  28.     //1、客户上传Word文档到服务器  
  29.        
  30.     //2、服务器调用OpenOffice程序打开上传的Word文档  
  31.        
  32.     //3、OpenOffice将Word文档另存为Html格式  
  33.   
  34.       
  35.     public File convertToHtml(String inputFile, String outputFile)  
  36.             throws FileNotFoundException {  
  37.          // 创建保存html的文件  
  38.         File wantFile = new File(outputFile + File.separator + new Date().getTime()  
  39.             + ".html");  
  40.         // 开启服务器  
  41.         startService();  
  42.         // 进行转换  
  43.         System.out.println("进行文档转换转换:" + inputFile + " --> " + outputFile);  
  44.         OfficeDocumentConverter converter = new OfficeDocumentConverter(  
  45.                 officeManager);  
  46.         converter.convert(new File(inputFile), wantFile);  
  47.         // 关闭服务器  
  48.         stopService();  
  49.         System.out.println();  
  50.         return wantFile;  
  51.   
  52.     }  
  53.   
  54.     // 打开服务器  
  55.     public static Boolean startService() {  
  56.         DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();  
  57.         try {  
  58.             System.out.println("准备启动服务....");  
  59.             configuration.setOfficeHome(OFFICE_HOME);// 设置OpenOffice.org安装目录  
  60.             configuration.setPortNumbers(port); // 设置转换端口,默认为8100  
  61.             configuration.setTaskExecutionTimeout(1000 * 60 * 5L);// 设置任务执行超时为5分钟  
  62.             configuration.setTaskQueueTimeout(1000 * 60 * 60 * 24L);// 设置任务队列超时为24小时  
  63.   
  64.             officeManager = configuration.buildOfficeManager();  
  65.             officeManager.start(); // 启动服务  
  66.             System.out.println("office转换服务启动成功!");  
  67.             return true;  
  68.         } catch (Exception ce) {  
  69.             System.out.println("office转换服务启动失败!详细信息:" + ce);  
  70.             return false;  
  71.         }  
  72.     }  
  73.   
  74.     // 关闭服务器  
  75.     public static void stopService() {  
  76.         System.out.println("关闭office转换服务....");  
  77.         if (officeManager != null) {  
  78.             officeManager.stop();  
  79.         }  
  80.         System.out.println("关闭office转换成功!");  
  81.     }  
  82.   
  83.     /* 
  84.      * 进行测试转换是否成功 
  85.      */  
  86.     public static void main(String[] args) {  
  87.         String inputFile = "c:\\test\\test.docx";  
  88.         String outputFile = "c:\\test";  
  89.         OpenOfficePdfConvert opc = new OpenOfficePdfConvert();  
  90.         try {  
  91.             opc.convertToHtml(inputFile,outputFile);  
  92.         } catch (FileNotFoundException e1) {  
  93.             e1.printStackTrace();  
  94.         }  
  95.         /*try { 
  96.             * 如果想看到不带HTML标签的字符串可以调用这个方法进行简化 
  97.    System.out.println(toHtmlString(inputFile, outputFile));} catch (FileNotFoundException e) { 
  98.             e.printStackTrace(); 
  99.         }*/  
  100.         System.out.println("恭喜您,转换成功...");  
  101.     }  
  102.   
  103.     /** 
  104.      * 将word转换成html文件,并且获取html文件代码。 
  105.      *  
  106.      * @param docFile 
  107.      *            需要转换的文档 
  108.      * @param filepath 
  109.      *            文档中图片的保存位置 
  110.      * @return 转换成功的html代码 
  111.      * @throws FileNotFoundException 
  112.      */  
  113.     public static String toHtmlString(String docFile, String filepath)  
  114.             throws FileNotFoundException {  
  115.         System.out.println("文档中图片的保存位置 ==>" + filepath);  
  116.         // 转换word文档  
  117.         OpenOfficePdfConvert opc = new OpenOfficePdfConvert();  
  118.         File htmlFile = opc.convertToHtml(docFile, filepath);  
  119.         // 获取html文件流  
  120.         StringBuffer htmlSb = new StringBuffer();  
  121.         try {  
  122.             BufferedReader br = new BufferedReader(new InputStreamReader(  
  123.                     new FileInputStream(htmlFile)));  
  124.             while (br.ready()) {  
  125.                 htmlSb.append(br.readLine());  
  126.             }  
  127.             br.close();  
  128.             // 删除临时文件  
  129.             // htmlFile.delete();  
  130.         } catch (FileNotFoundException e) {  
  131.             e.printStackTrace();  
  132.         } catch (IOException e) {  
  133.             e.printStackTrace();  
  134.         }  
  135.         // HTML文件字符串  
  136.         String htmlStr = htmlSb.toString();  
  137.         // 返回经过清洁的html文本  
  138.         return clearFormat(htmlStr, filepath);  
  139.     }  
  140.   
  141.     /** 
  142.      * 清除一些不需要的html标记 
  143.      *  
  144.      * @param htmlStr  带有复杂html标记的html语句 
  145.      *          
  146.      * @return 去除了不需要html标记的语句 
  147.      */  
  148.     protected static String clearFormat(String htmlStr, String docImgPath) {  
  149.         // 获取body内容的正则  
  150.         String bodyReg = "<BODY .*</BODY>";  
  151.         Pattern bodyPattern = Pattern.compile(bodyReg);  
  152.         Matcher bodyMatcher = bodyPattern.matcher(htmlStr);  
  153.         if (bodyMatcher.find()) {  
  154.             // 获取BODY内容,并转化BODY标签为DIV  
  155.             htmlStr = bodyMatcher.group().replaceFirst("<BODY", "<DIV")  
  156.                     .replaceAll("</BODY>", "</DIV>");  
  157.         }  
  158.         // 调整图片地址  
  159.         htmlStr = htmlStr.replaceAll("<IMG SRC=\"", "<IMG SRC=\"" + docImgPath  
  160.                 + "/");  
  161.         // 把<P></P>转换成</div></div>保留样式  
  162.         // content = content.replaceAll("(<P)([^>]*>.*?)(<\\/P>)",  
  163.         // "<div$2</div>");  
  164.         // 把<P></P>转换成</div></div>并删除样式  
  165.         htmlStr = htmlStr.replaceAll("(<P)([^>]*)(>.*?)(<\\/P>)", "<p$3</p>");  
  166.         // 删除不需要的标签  
  167.         htmlStr = htmlStr  
  168.                 .replaceAll(  
  169.                         "<[/]?(font|FONT|span|SPAN|xml|XML|del|DEL|ins|INS|meta|META|[ovwxpOVWXP]:\\w+)[^>]*?>",  
  170.                         "");  
  171.         // 删除不需要的属性  
  172.         htmlStr = htmlStr  
  173.                 .replaceAll(  
  174.                         "<([^>]*)(?:lang|LANG|class|CLASS|style|STYLE|size|SIZE|face|FACE|[ovwxpOVWXP]:\\w+)=(?:'[^']*'|\"\"[^\"\"]*\"\"|[^>]+)([^>]*)>",  
  175.                         "<$1$2>");  
  176.         return htmlStr;  
  177.     }  
  178. }  


主要类说明:
OfficeManager是一个接口,主要定义了三个方法:
 1.public void start( )启动OpenOffice服务
 2.public void stop( )停止OpenOffice服务
 3.public void execute(OfficeTask task)执行转换任务
 
 DefaultOfficeManagerConfiguration是一个实现了OfficeManager接口的实体类,其提供了相关方法配置OpenOffice.org,比如:
 
 public DefaultOfficeManagerConfiguration setOfficeHome(String officeHome)设置OpenOffice.org或者LibreOffice安装目录,
  windows下默认值为” C:\Program Files\OpenOffice.org 3”(LibreOffice进行相应更改),因此如果OpenOffice.org安装在别的目录,必须设置此项。
 
 public DefaultOfficeManagerConfiguration setConnectionProtocol(OfficeConnectionProtocol conn)设置连接协议,确定使用管道通信,还是socekt通信。
 
 pubcli DefaultOfficeManagerConfiguration setTemplateProfileDir(File templateProfileDir)设定临时目录。
 
 除以上几个方法之外,DefaultOfficeManagerConfiguration还提供了别的配置OpenOffice.org的方法,具体方法可以查询JODConverter API手册。
 配置完之后,必须要执行方法buildOfficeManager(),实现真正的配置。
 
 OfficeDocumentConverter中主要包含convert方法,该方法实际上调用的是实现OfficeManager接口的类中的execute方法。

   整体看起来还是比较简单的,但对自己也是一种提高,在此特别感谢肖恩也有梦想http://www.cnblogs.com/luckyxiaoxuan/archive/2012/06/14/2549012.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多