欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java实现附件预览(openoffice+swftools+flexpaper)实例

程序员文章站 2024-03-11 22:11:19
本文主要介绍了java实现附件预览,需要用到openoffice、swftools、flexpaper,具体步骤如下: 1.概述 主要原理 1.通过第三方工具open...

本文主要介绍了java实现附件预览,需要用到openoffice、swftools、flexpaper,具体步骤如下:

1.概述

主要原理

1.通过第三方工具openoffice,将word、excel、ppt、txt等文件转换为pdf文件

2.通过swftools将pdf文件转换成swf格式的文件

3.通过flexpaper文档组件在页面上进行展示

2.安装包下载

1.openoffice是apache下的一个开放免费的文字处理软件

   下载地址:apache oppenoffice 官网下载 版本-3.4.1

2.swftools是一组用来处理flash的swf文件的工具包,我们使用它将pdf文件转成swf文件!

   下载地址:swftools官网下载 swftools-2013-04-09-1007.exe 

3.flexpaper是一个开源轻量级的在浏览器上显示各种文档的组件

   下载地址:flexpaper官网下载 版本1.5.1 

4.jodconverter一个java的opendocument 文件转换器,在此我们只用到它的jar包

   下载地址:jodcconverter下载 

3.安装文件

1.将所下载的文件(jodconverter除外)进行安装,盘符可随自己设定!需要注意的是在openoffice安装完成后,当我们使用它时,需将它的服务打开。在次我们需要以命令的方式打开:

打开dos窗口,进入openoffice安装盘符,输入以下代码来启动服务:

soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard

注意最后一个命令前边的‘—',可不要写错!服务起不来,项目可是继续不下去的哦.

官网启动服务截图如下:

java实现附件预览(openoffice+swftools+flexpaper)实例

本地截图:

java实现附件预览(openoffice+swftools+flexpaper)实例

3.开发过程

1.新建项目,将flexpaper文件中的js文件夹(包含了flexpaper_flash_debug.js,flexpaper_flash.js,jquery.js,这三个js文件主要是预览swf文件的插件)拷贝至网站根目录;将flexpaperviewer.swf拷贝至网站根目录下(该文件主要是用在网页中播放swf文件的播放器),目录结构如下图:

java实现附件预览(openoffice+swftools+flexpaper)实例

注:需创建upload文件夹

2.创建fileupload.jsp

<%@ page language="java" contenttype="text/html; charset=utf-8" 
  pageencoding="utf-8"%> 
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="content-type" content="text/html; charset=utf-8"> 
<title>文档在线预览系统</title> 
<style> 
  body {margin-top:100px;background:#fff;font-family: verdana, tahoma;} 
  a {color:#ce4614;} 
  #msg-box {color: #ce4614; font-size:0.9em;text-align:center;} 
  #msg-box .logo {border-bottom:5px solid #ece5d9;margin-bottom:20px;padding-bottom:10px;} 
  #msg-box .title {font-size:1.4em;font-weight:bold;margin:0 0 30px 0;} 
  #msg-box .nav {margin-top:20px;} 
</style> 
 
</head> 
<body> 
<div id="msg-box"> 
  <form name="form1" method="post" enctype="multipart/form-data" action="docuploadconvertaction.jsp"> 
    <div class="title"> 
      请上传要处理的文件,过程可能需要几分钟,请稍候片刻。 
    </div> 
    <p> 
      <input name="file1" type="file"> 
    </p> 
    <p> 
      <input type="submit" name="submit" value="上传"> 
    </p> 
  </form > 
</div> 
</body> 
</html>

3.创建转换页docuploadconvertaction.jsp

<%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%> 
 
<%@page import="java.io.*"%> 
<%@page import="java.util.enumeration"%> 
<%@page import="com.oreilly.servlet.multipartrequest"%> 
<%@page import="com.oreilly.servlet.multipart.defaultfilerenamepolicy"%> 
<%@page import="com.cectsims.util.docconverter"%> 
<% 
//文件上传采用cos组件上传,可更换为commons-fileupload上传,文件上传后,保存在upload文件夹 
//获取文件上传路径 
string savedirectory =application.getrealpath("/")+"upload"; 
//打印上传路径信息 
system.out.println(savedirectory); 
//每个文件最大50m 
int maxpostsize = 50 * 1024 * 1024 ; 
//采用cos缺省的命名策略,重名后加1,2,3...如果不加dfp重名将覆盖 
defaultfilerenamepolicy dfp = new defaultfilerenamepolicy(); 
//response的编码为"utf-8",同时采用缺省的文件名冲突解决策略,实现上传,如果不加dfp重名将覆盖 
multipartrequest multi = new multipartrequest(request, savedirectory, maxpostsize,"utf-8",dfp); 
//multipartrequest multi = new multipartrequest(request, savedirectory, maxpostsize,"utf-8"); 
//输出反馈信息 
 enumeration files = multi.getfilenames(); 
   while (files.hasmoreelements()) { 
    system.err.println("ccc"); 
    string name = (string)files.nextelement(); 
    file f = multi.getfile(name); 
    if(f!=null){ 
     string filename = multi.getfilesystemname(name); 
     //获取上传文件的扩展名 
     string extname=filename.substring(filename.lastindexof(".")+1); 
     //文件全路径 
     string lastfilename= savedirectory+"\\" + filename; 
     //获取需要转换的文件名,将路径名中的'\'替换为'/' 
     string converfilename = savedirectory.replaceall("\\\\", "/")+"/"+filename; 
     system.out.println(converfilename); 
     //调用转换类docconverter,并将需要转换的文件传递给该类的构造方法 
     docconverter d = new docconverter(converfilename); 
     //调用conver方法开始转换,先执行doc2pdf()将office文件转换为pdf;再执行pdf2swf()将pdf转换为swf; 
     d.conver(); 
     //调用getswfpath()方法,打印转换后的swf文件路径 
     system.out.println(d.getswfpath()); 
     //生成swf相对路径,以便传递给flexpaper播放器 
     string swfpath = "upload"+d.getswfpath().substring(d.getswfpath().lastindexof("/")); 
     system.out.println(swfpath); 
     //将相对路径放入sessio中保存 
     session.setattribute("swfpath", swfpath); 
     out.println("上传的文件:"+lastfilename); 
     out.println("文件类型"+extname); 
     out.println("<hr>"); 
    } 
   } 
 
%> 
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="content-type" content="text/html; charset=utf-8"> 
<title>insert title here</title> 
<style> 
  body {margin-top:100px;background:#fff;font-family: verdana, tahoma;} 
  a {color:#ce4614;} 
  #msg-box {color: #ce4614; font-size:0.9em;text-align:center;} 
  #msg-box .logo {border-bottom:5px solid #ece5d9;margin-bottom:20px;padding-bottom:10px;} 
  #msg-box .title {font-size:1.4em;font-weight:bold;margin:0 0 30px 0;} 
  #msg-box .nav {margin-top:20px;} 
</style> 
</head> 
<body> 
  <div> 
    <form name="viewform" id="form_swf" action="documentview.jsp" method="post"> 
      <input type='submit' value='预览' class='button submit'/> 
    </form> 
  </div> 
</body> 
</html>

创建查看页documentview.jsp

<%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%> 
<% 
  string swffilepath=session.getattribute("swfpath").tostring(); 
%> 
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="content-type" content="text/html; charset=utf-8"> 
<script type="text/javascript" src="js/jquery.js"></script> 
<script type="text/javascript" src="js/flexpaper_flash.js"></script> 
<script type="text/javascript" src="js/flexpaper_flash_debug.js"></script> 
<style type="text/css" media="screen">  
      html, body { height:100%; } 
      body { margin:0; padding:0; overflow:auto; }   
      #flashcontent { display:none; } 
    </style>  
 
<title>文档在线预览系统</title> 
</head> 
<body>  
    <div style="position:absolute;left:50px;top:10px;"> 
      <a id="viewerplaceholder" style="width:820px;height:650px;display:block"></a> 
       
      <script type="text/javascript">  
        var fp = new flexpaperviewer(   
             'flexpaperviewer', 
             'viewerplaceholder', { config : { 
             swffile : escape('<%=swffilepath%>'), 
             scale : 0.6,  
             zoomtransition : 'easeout', 
             zoomtime : 0.5, 
             zoominterval : 0.2, 
             fitpageonload : true, 
             fitwidthonload : false, 
             fullscreenasmaxwindow : false, 
             progressiveloading : false, 
             minzoomsize : 0.2, 
             maxzoomsize : 5, 
             searchmatchall : false, 
             initviewmode : 'singlepage', 
              
             viewmodetoolsvisible : true, 
             zoomtoolsvisible : true, 
             navtoolsvisible : true, 
             cursortoolsvisible : true, 
             searchtoolsvisible : true, 
             
             localechain: 'en_us' 
             }}); 
      </script>       
    </div> 
</body> 
</html>

5.创建转换类docconverter.java

package com.cectsims.util; 
import java.io.bufferedinputstream; 
import java.io.file; 
import java.io.ioexception; 
import java.io.inputstream; 
 
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; 
 
/** 
 * doc docx格式转换 
 */ 
public class docconverter { 
  private static final int environment = 1;// 环境 1:windows 2:linux 
  private string filestring;// (只涉及pdf2swf路径问题) 
  private string outputpath = "";// 输入路径 ,如果不设置就输出在默认的位置 
  private string filename; 
  private file pdffile; 
  private file swffile; 
  private file docfile; 
   
  public docconverter(string filestring) { 
    ini(filestring); 
  } 
 
  /** 
   * 重新设置file 
   * 
   * @param filestring 
   */ 
  public void setfile(string filestring) { 
    ini(filestring); 
  } 
 
  /** 
   * 初始化 
   * 
   * @param filestring 
   */ 
  private void ini(string filestring) { 
    this.filestring = filestring; 
    filename = filestring.substring(0, filestring.lastindexof(".")); 
    docfile = new file(filestring); 
    pdffile = new file(filename + ".pdf"); 
    swffile = new file(filename + ".swf"); 
  } 
   
  /** 
   * 转为pdf 
   * 
   * @param file 
   */ 
  private void doc2pdf() throws exception { 
    if (docfile.exists()) { 
      if (!pdffile.exists()) { 
        openofficeconnection connection = new socketopenofficeconnection(8100); 
        try { 
          connection.connect(); 
          documentconverter converter = new openofficedocumentconverter(connection); 
          converter.convert(docfile, pdffile); 
          // close the connection 
          connection.disconnect(); 
          system.out.println("****pdf转换成功,pdf输出:" + pdffile.getpath()+ "****"); 
        } catch (java.net.connectexception e) { 
          e.printstacktrace(); 
          system.out.println("****swf转换器异常,openoffice服务未启动!****"); 
          throw e; 
        } catch (com.artofsolving.jodconverter.openoffice.connection.openofficeexception e) { 
          e.printstacktrace(); 
          system.out.println("****swf转换器异常,读取转换文件失败****"); 
          throw e; 
        } catch (exception e) { 
          e.printstacktrace(); 
          throw e; 
        } 
      } else { 
        system.out.println("****已经转换为pdf,不需要再进行转化****"); 
      } 
    } else { 
      system.out.println("****swf转换器异常,需要转换的文档不存在,无法转换****"); 
    } 
  } 
   
  /** 
   * 转换成 swf 
   */ 
  @suppresswarnings("unused") 
  private void pdf2swf() throws exception { 
    runtime r = runtime.getruntime(); 
    if (!swffile.exists()) { 
      if (pdffile.exists()) { 
        if (environment == 1) {// windows环境处理 
          try { 
            process p = r.exec("d:/program files/swftools/pdf2swf.exe "+ pdffile.getpath() + " -o "+ swffile.getpath() + " -t 9"); 
            system.out.print(loadstream(p.getinputstream())); 
            system.err.print(loadstream(p.geterrorstream())); 
            system.out.print(loadstream(p.getinputstream())); 
            system.err.println("****swf转换成功,文件输出:" 
                + swffile.getpath() + "****"); 
            if (pdffile.exists()) { 
              pdffile.delete(); 
            } 
 
          } catch (ioexception e) { 
            e.printstacktrace(); 
            throw e; 
          } 
        } else if (environment == 2) {// linux环境处理 
          try { 
            process p = r.exec("pdf2swf " + pdffile.getpath() 
                + " -o " + swffile.getpath() + " -t 9"); 
            system.out.print(loadstream(p.getinputstream())); 
            system.err.print(loadstream(p.geterrorstream())); 
            system.err.println("****swf转换成功,文件输出:" 
                + swffile.getpath() + "****"); 
            if (pdffile.exists()) { 
              pdffile.delete(); 
            } 
          } catch (exception e) { 
            e.printstacktrace(); 
            throw e; 
          } 
        } 
      } else { 
        system.out.println("****pdf不存在,无法转换****"); 
      } 
    } else { 
      system.out.println("****swf已经存在不需要转换****"); 
    } 
  } 
 
  static string loadstream(inputstream in) throws ioexception { 
 
    int ptr = 0; 
    in = new bufferedinputstream(in); 
    stringbuffer buffer = new stringbuffer(); 
 
    while ((ptr = in.read()) != -1) { 
      buffer.append((char) ptr); 
    } 
 
    return buffer.tostring(); 
  } 
  /** 
   * 转换主方法 
   */ 
  @suppresswarnings("unused") 
  public boolean conver() { 
 
    if (swffile.exists()) { 
      system.out.println("****swf转换器开始工作,该文件已经转换为swf****"); 
      return true; 
    } 
 
    if (environment == 1) { 
      system.out.println("****swf转换器开始工作,当前设置运行环境windows****"); 
    } else { 
      system.out.println("****swf转换器开始工作,当前设置运行环境linux****"); 
    } 
    try { 
      doc2pdf(); 
      pdf2swf(); 
    } catch (exception e) { 
      e.printstacktrace(); 
      return false; 
    } 
 
    if (swffile.exists()) { 
      return true; 
    } else { 
      return false; 
    } 
  } 
 
  /** 
   * 返回文件路径 
   * 
   * @param s 
   */ 
  public string getswfpath() { 
    if (swffile.exists()) { 
      string tempstring = swffile.getpath(); 
      tempstring = tempstring.replaceall("\\\\", "/"); 
      return tempstring; 
    } else { 
      return ""; 
    } 
 
  } 
  /** 
   * 设置输出路径 
   */ 
  public void setoutputpath(string outputpath) { 
    this.outputpath = outputpath; 
    if (!outputpath.equals("")) { 
      string realname = filename.substring(filename.lastindexof("/"), 
          filename.lastindexof(".")); 
      if (outputpath.charat(outputpath.length()) == '/') { 
        swffile = new file(outputpath + realname + ".swf"); 
      } else { 
        swffile = new file(outputpath + realname + ".swf"); 
      } 
    } 
  } 
 
}

6.部署发布

启动tomcat,部署当前web应用

地址栏输入http://localhost:8080/ctcesims/documentupload.jsp 如下图:

java实现附件预览(openoffice+swftools+flexpaper)实例

单击预览按钮,就会生成预览界面,如下图:

java实现附件预览(openoffice+swftools+flexpaper)实例

4.常见问题

若出现swf无法预览,请访问

将生成swf的文件夹设置为信任文件位置。
以下给出 flexpaper 2.1.9 的不同之处:初始化方式改变,若文件目录与项目目录不在一起,可将附件目录在服务器中设置为虚拟目录

<%@ page language="java" contenttype="text/html; charset=utf-8"
  pageencoding="utf-8"%>
<%
  //string swffilepath=session.getattribute("swfpath").tostring();
%>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/flexpaper.js"></script>
<script type="text/javascript" src="js/flexpaper_handlers.js"></script>
<style type="text/css" media="screen"> 
      html, body  { height:100%; }
      body { margin:0; padding:0; overflow:auto; }  
      #flashcontent { display:none; }
    </style> 

<title>文档在线预览系统</title>
</head>
<body> 
    <div style="position:absolute;left:50px;top:10px;">
      <div id="documentviewer" class="flexpaper_viewer" style="width:770px;height:500px"></div>
 
      <script type="text/javascript"> 

      var startdocument = "paper";

      $('#documentviewer').flexpaperviewer(
          { config : {

            swffile : 'upload/ddd3.swf',

            scale : 0.6,
            zoomtransition : 'easeout',
            zoomtime : 0.5,
            zoominterval : 0.2,
            fitpageonload : true,
            fitwidthonload : false,
            fullscreenasmaxwindow : false,
            progressiveloading : false,
            minzoomsize : 0.2,
            maxzoomsize : 5,
            searchmatchall : false,
            initviewmode : 'portrait',
            renderingorder : 'flash',
            startatpage : '',

            viewmodetoolsvisible : true,
            zoomtoolsvisible : true,
            navtoolsvisible : true,
            cursortoolsvisible : true,
            searchtoolsvisible : true,
            wmode : 'window',
            localechain: 'en_us'
          }}
      );
    
      </script>      
    </div>
</body>
</html>

最后,若需要去除打印功能及logo,可重新编译 flexpaper 的 flash文件,网上也有下载

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。