openoffice+jquery.media.js实现文档在线预览

1.功能:

  实现Windows环境下文档在线预览功能,支持.doc、.docx、.xls、.xlsx、.ppt、.pptx、.pdf格式的文档,对IE浏览器不太兼容。如要实现Linux环境下文档在线预览功能,改变相应配置和代码,要安装Linux版的OpenOffice。

2.所需组件:

  (1)OpenOffice4.0.1 :

      下载地址:http://pan.baidu.com/s/1hsQkhzm

  (2)jquery.media.js:

      下载地址:http://pan.baidu.com/s/1c2vQcCS

  (3)所需jar:

  

  下载地址:http://pan.baidu.com/s/1micCZBa

3.具体实现:

  (1)设置OpenOffice的配置文件openOfficeService.properties

OO_HOME = G:/java_app_common/OpenOffice4/program/
oo_host = 127.0.0.1
oo_port =8100

  (2)jsp页面

 1 <script type="text/javascript" src="/js/jquery.media.js"></script>
 2 <script language="javascript">
 3     //设置预览框的大小
 4     $(function() {
 5             $("#media").media({width:1000, height:950});
 6         });
 7 </script>
 8 <body>
 9     <div>
10         <a class="media" id="media" href="生成的pdf文件的路径"></a>
11     </div>
12 </body>

  (3)java代码

  DocConverter.java转换类

  2
  3 import java.io.BufferedInputStream;
  4 import java.io.BufferedOutputStream;
  5 import java.io.BufferedReader;
  6 import java.io.File;
  7 import java.io.FileInputStream;
  8 import java.io.FileOutputStream;
  9 import java.io.IOException;
 10 import java.io.InputStream;
 11 import java.io.InputStreamReader;
 12 import java.util.ResourceBundle;
 13
 14 import com.artofsolving.jodconverter.DocumentConverter;
 15 import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
 16 import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
 17 import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
 18
 19 public class DocConverter {
 20
 21     private String SWFTools_Windows = "G:/java_app_common/SWFTools/pdf2swf.exe ";
 22 //    private String SWFTools_Linux = "F:/sortware/testingsoftware/SWFTools/pdf2swf.exe ";
 23     private static final int environment = 1;// 环境1:windows,2:linux(涉及pdf2swf路径问题)
 24     private String fileString;
 25     private String outputPath = "";// 输入路径,如果不设置就输出在默认位置
 26     private String fileName;
 27     private File pdfFile;
 28     private File swfFile;
 29     private File docFile;
 30     private File odtFile;
 31
 32
 33     public DocConverter(String fileString) {
 34         ini(fileString);
 35     }
 36
 37     /*
 38      * 重新设置 file @param fileString
 39      */
 40     public void setFile(String fileString) {
 41         ini(fileString);
 42     }
 43
 44     /*
 45      * 初始化 @param fileString
 46      */
 47     private void ini(String fileString) {
 48          try {
 49              System.out.println("fileString: " + fileString);
 50              this.fileString = fileString;
 51
 52              fileName = fileString.substring(0, fileString.lastIndexOf("/"));
 53              docFile = new File(fileString);
 54              String s = fileString.substring(fileString.lastIndexOf("/") + 1,fileString.lastIndexOf("."));
 55              fileName = fileName + "/" + s;
 56              // 用于处理TXT文档转化为PDF格式乱码,获取上传文件的名称(不需要后面的格式)
 57              String txtName = fileString.substring(fileString.lastIndexOf("."));
 58              // 判断上传的文件是否是TXT文件
 59              if (txtName.equalsIgnoreCase(".txt")) {
 60                  // 定义相应的ODT格式文件名称
 61                  odtFile = new File(fileName + ".odt");
 62                  // 将上传的文档重新copy一份,并且修改为ODT格式,然后有ODT格式转化为PDF格式
 63                  this.copyFile(docFile, odtFile);
 64                  pdfFile = new File(fileName + ".pdf"); // 用于处理PDF文档
 65              } else if (txtName.equals(".pdf") || txtName.equals(".PDF")) {
 66                  pdfFile = new File(fileName + ".bac.pdf");
 67                  this.copyFile(docFile, pdfFile);
 68              } else {
 69                  pdfFile = new File(fileName + ".pdf");
 70                  //this.copyFile(docFile, pdfFile);
 71                  System.out.println("pdfFile: " + pdfFile.getPath());
 72              }
 73              swfFile = new File(fileName + ".swf");
 74          } catch (Exception e) {
 75              e.printStackTrace();
 76          }
 77      }
 78
 79     /**
 80      * @Title: copyFile
 81      * @Description: TODO
 82      * @param: @param docFile2
 83      * @param: @param odtFile2
 84      * @return: void
 85      * @author: hl 87      * @throws
 88      */
 89     private void copyFile(File sourceFile,File targetFile)throws Exception{
 90         //新建文件输入流并对它进行缓冲 
 91         FileInputStream input = new FileInputStream(sourceFile);
 92         BufferedInputStream inBuff = new BufferedInputStream(input);
 93         // 新建文件输出流并对它进行缓冲
 94         FileOutputStream output = new FileOutputStream(targetFile);
 95         BufferedOutputStream outBuff  = new BufferedOutputStream(output);
 96         // 缓冲数组 
 97         byte[]b = new byte[1024 * 1];
 98         int len;
 99         while((len = inBuff.read(b)) != -1){
100             outBuff.write(b,0,len);
101         }
102         // 刷新此缓冲的输出流
103         outBuff.flush();
104         // 关闭流
105         inBuff.close();
106         outBuff.close();
107         output.close();
108         input.close();
109     }
110
111     /*
112      * 转为PDF @param file
113      */
114     private void doc2pdf() throws Exception {
115         System.out.println("此文件是否存在:" + docFile.exists());
116         if (docFile.exists()) {
117             if (!pdfFile.exists()) {
118                 OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
119                 ResourceBundle rb = ResourceBundle.getBundle("openOfficeService");
120                 String OpenOffice_HOME = rb.getString("OO_HOME");
121                 String host_Str = rb.getString("oo_host");
122                 String port_Str = rb.getString("oo_port");
123                 try {
124                     // 自动启动OpenOffice的服务    soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
125                     String command = OpenOffice_HOME
126                             + "soffice -headless -accept=\"socket,host="
127                             + host_Str + ",port=" + port_Str + ";urp;\"" + "-nofirststartwizard";
128                     System.out.println("###\n" + command);
129                     Process pro = Runtime.getRuntime().exec(command);
130                     // 连接openoffice服务
131 //                    OpenOfficeConnection connection = new SocketOpenOfficeConnection(
132 //                            host_Str, Integer.parseInt(port_Str));
133                     connection.connect();
134                     DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
135                     converter.convert(docFile, pdfFile);
136                     // close the connection
137                     connection.disconnect();
138                     pro.destroy();
139                     System.out.println("****pdf转换成功,PDF输出:" + pdfFile.getPath() + "****");
140                 } catch (java.net.ConnectException e) {
141                     // ToDo Auto-generated catch block
142                     e.printStackTrace();
143                     System.out.println("****swf转换异常,openoffice服务未启动!****");
144                     doc2pdf();
145                     throw e;
146                 } catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {
147                     e.printStackTrace();
148                     System.out.println("****swf转换器异常,读取转换文件失败****");
149                     doc2pdf();
150                     throw e;
151                 } catch (Exception e) {
152                     e.printStackTrace();
153                     doc2pdf();
154                     throw e;
155                 }
156             } else {
157                 System.out.println("****已经转换为pdf,不需要再进行转化****");
158             }
159         } else {
160             System.out.println("****swf转换器异常,需要转换的文档不存在,无法转换****");
161         }
162     }
163
164     /*
165      * 转换成swf,此方法未用到
166      */
167     @SuppressWarnings("unused")
168     private void pdf2swf() throws Exception {
169         Runtime r = Runtime.getRuntime();
170         if (!swfFile.exists()) {
171             if (pdfFile.exists()) {
172                 if (environment == 1){// windows环境处理
173                     try {
174                         // 这里根据SWFTools安装路径需要进行相应更改
175                         Process p = r.exec(SWFTools_Windows + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9");
176                         //Process p = r.exec(SWFTools_Windows + pdfFile.getPath() + " -s languageedir=G:/java_app_common/xpdf/xpdf-chinese-simplified " + " -o " + swfFile.getPath() + " -T 9");
177
178                         System.out.print(loadStream(p.getInputStream()));
179                         System.err.print(loadStream(p.getErrorStream()));
180                         System.out.print(loadStream(p.getInputStream()));
181                         System.err.println("****swf转换成功,文件输出:" + swfFile.getPath() + "****");
182 //                        if (pdfFile.exists()) {
183 //                            pdfFile.delete();
184 //                        }
185                     } catch (Exception e) {
186 //                        e.printStackTrace();
187                         System.out.println("找到你了");
188                         throw e;
189                     }
190                 } else if (environment == 2){// linux环境处理
191                     try {
192                         Process p = r.exec("pdf2swf " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9");
193                         System.out.print(loadStream(p.getInputStream()));
194                         System.err.print(loadStream(p.getErrorStream()));
195                         System.err.println("****swf转换成功,文件输出:" + swfFile.getPath() + "****");
196                         if (pdfFile.exists()) {
197                             pdfFile.delete();
198                         }
199                     } catch (Exception e) {
200                         e.printStackTrace();
201                         throw new RuntimeException();
202                     }
203                 }
204             } else {
205                 System.out.println("****pdf不存在,无法转换****");
206             }
207         } else {
208             System.out.println("****swf已存在不需要转换****");
209         }
210     }
211
212     static String loadStream(InputStream in) throws IOException {
213         int ptr = 0;
214         //把InputStream字节流 替换为BufferedReader字符流 2013-07-17修改
215         BufferedReader reader = new BufferedReader(new InputStreamReader(in));
216         StringBuilder buffer = new StringBuilder();
217         while ((ptr = reader.read()) != -1) {
218             buffer.append((char) ptr);
219         }
220         return buffer.toString();
221     }
222
223     /*
224      * 转换主方法
225      */
226     public boolean conver() {
227 //        if (swfFile.exists()) {
228 //            System.out.println("****swf转换器开始工作,该文件已经转换为swf****");
229 //            return true;
230 //        }
231
232         if (environment == 1) {
233             System.out.println("****swf转换器开始工作,当前设置运行环境windows****");
234         } else {
235             System.out.println("****swf转换器开始工作,当前设置运行环境linux****");
236         }
237
238         try {
239             doc2pdf();
240             //pdf2swf();//以前找的资料是要把PDF转换为swf格式的文件再用flexpaper预览,此种方法问题较多,所以没用,改变为只转换成pdf,然后用jquery.media.js直接预览pdf
241             return true;
242         } catch (Exception e) {
243             // TODO: Auto-generated catch block
244             e.printStackTrace();
245             return false;
246         }
247
248 //        if (swfFile.exists()) {
249 //            return true;
250 //        } else {
251 //            return false;
252 //        }
253     }
254
255     /*
256      * 返回文件路径 @param s
257      */
258     public String getswfPath() {
259         if (swfFile.exists()) {
260             String tempString = swfFile.getPath();
261             tempString = tempString.replaceAll("\\\\", "/");
262             System.out.println(tempString);
263
264             return tempString;
265         } else {
266             return "";
267         }
268     }
269
270     /*
271      * 设置输出路径
272      */
273     public void setOutputPath(String outputPath) {
274         this.outputPath = outputPath;
275         if (!outputPath.equals("")) {
276             String realName = fileName.substring(fileName.lastIndexOf("/"), fileName.lastIndexOf("."));
277             if (outputPath.charAt(outputPath.length()) == ‘/‘) {
278                 swfFile = new File(outputPath + realName + ".swf");
279             } else {
280                 swfFile = new File(outputPath + realName + ".swf");
281             }
282         }
283     }
284
285     public static void main(String s[]) {
286         DocConverter d = new DocConverter("G:/java_app_common/Tomcat/apache-tomcat-6.0.45/webapps/project_data/vc_space_file/1497492316364495484.docx");
287         d.conver();
288     }
289 }

  部分controller代码:

 1 //判断文件是否为PDF格式,如是pdf格式直接预览,如不是pdf格式转换成pdf格式再预览
 2 if(fileName.substring(fileName.lastIndexOf(".")).equals(".pdf") || fileName.substring(fileName.lastIndexOf(".")).equals(".PDF"))
 3 {
 4   //直接把此文件的路径传到jsp页面
 5 }else
 6 {
 7     //调用转换类DocConverter,并将需要转换的文件传递给该类的构造方法
 8     DocConverter d = new DocConverter(文件路径);
 9     //调用conver方法开始转换,执行doc2pdf()将office文件转换为pdf
10     System.out.println("调用conver方法开始转换...");
11     d.conver();
12     //将转换后的pdf格式的文件的路径传到jsp页面
13 }

  

  

  

  

时间: 2024-08-06 07:56:37

openoffice+jquery.media.js实现文档在线预览的相关文章

Java实现文档在线预览(openoffice+swfTools+FlexPaper)

      文档在线预览在项目中早就完成了,后来又经过了一次优化.但是一直都没时间去记录遇到的问题,文档在线预览的详细步骤可以参考http://blog.csdn.net/u013614451/article/details/24261503,感谢博主写了这么好的文章帮助我完成了项目中主要的模块.下面是文档转换的工具类DocConvert.java,并标注出我修改的部分. package com.he.util; import java.io.BufferedInputStream; impor

文档在线预览开源实现方案一:OpenOffice + SwfTools + FlexPaper

在文档在线预览方面,项目组之前使用的是Microsoft office web apps, 由于该方案需要按照微软License付费,项目经理要我预研一个文档在线预览的开源实现方案.仔细钻入该需求发现其实文档在线预览的开源方案还是挺多的,今天研究的方案一采用的技术栈是:OpenOffice +SwfTools + FlexPaper, 这种方案是目前比较成熟的方案,很多网站采用该方案来实现在线预览的功能.这种方案的思路是这样的: 通过OpenOffice的服务将office文档及文本文档转换为p

Java实现word文档在线预览,读取office文件

想要实现word或者其他office文件的在线预览,大部分都是用的两种方式,一种是使用openoffice转换之后再通过其他插件预览,还有一种方式就是通过POI读取内容然后预览. 一.使用openoffice方式实现word预览 主要思路是: 1.通过第三方工具openoffice,将word.excel.ppt.txt等文件转换为pdf文件 2.通过swfTools将pdf文件转换成swf格式的文件 3.通过FlexPaper文档组件在页面上进行展示 我使用的工具版本: openof:3.4.

office转html文档在线预览

要想实现office文档在线预览,可以使用红樱枫软件公司开发的数据格式转换软件HTML Filter,实现MS Office系列文档到HTML的快速转换,通过浏览器浏览HTML的内容.该产品可以将 word转html, excel转html, ppt转html,方便用户在不方便下载附件的时候,可以直接在线预览文档内容,应用在邮箱文档附件预览.云存储.云网盘的文档预览等方面. 本产品采用了先进的多语言.多平台.多线程的设计理念,支持多国语言,多种操作系统,提供了多种形式的API功能接口,便于用户使

轻松便捷的文档在线预览工具

北京博信施科技有限公司是一家专注于Office文档在线预览及PDF文档在线预览服务的专业提供商,依据HTML标准的4.01版本规范,研制开发出Microsoft Word.Excel.Powerpoint文档转换HTML文件格式以及Adobe PDF文件转换HTML文件格式的软件产品.实现Microsoft Word文档在线预览.Excel表格在线预览.Powerpoint演示文档在线预览及Adobe PDF文档在线预览,完美呈现Microsoft Office及Adobe PDF文档原始样式和

office文档在线预览 (doc、docx、ppt、pptx、xls、xlsx)

要想实现office文档在线预览,可以使用红樱枫软件公司开发的数据格式转换软件HTML Filter,该产品可以以程序库的形式提供给用户,提供各种程序接口,如:C/C++.Java..Net等接口,供用户将软件镶嵌在自己的系统中.通过调用本产品的提供的API功能接口,实现MS Office系列文档到HTML的快速转换.本产品在国内外得到了广泛的应用,在国内有腾讯.搜狐等多家知名企业使用本产品.对多种文档进行统一管理,编辑,检索和浏览.用户可以使用本产品,十分便利的将office文档Word,Ex

EDU-paas文档在线预览工具

本软件为edu-paas的文档在线预览,为开源软件.支持所有office文档在线预览. 文件类型全,转化快,跨平台响应式预览,兼容所有访问端. 下载地址 live.edu-paas.com/dowmCenter/EDUDocumentOnlinePreviewToolV.1.zip 源程序下载地址 live.edu-paas.com/dowmCenter/EDUFbDocumentOnlinePreviewToolV.1.zip 发布好的web 1 string serverUrl = "htt

仿百度文库实现文档在线预览

原文:仿百度文库实现文档在线预览 源代码下载地址:http://www.zuidaima.com/share/1550463679990784.htm 挺不错的,这是别人群里共享的,我现在共享给牛牛们

asp.net如何实现word文档在线预览

原文:asp.net如何实现word文档在线预览 实现方式:office文档转html,再在浏览器里面在线浏览 1.首先引入com组件中office库,然后在程序集扩展中引入word的dll 2.将Microsoft.Office.Interop.Word的嵌入互操作类型设置为 false,如图 3.主要代码 C# 代码   复制 using System; using System.Collections.Generic; using System.Linq; using System.Web