文档文件等网页端预览功能

来源:互联网 发布:怀化网络干部学院 编辑:程序博客网 时间:2024/06/06 12:38

要实现wordpptexcelpdf等文档在web应用端预览功能,目前一般做法为:

  在页面的显示效果:

 
主要用的工具:
  Openoffice4(windows、linux);  SWFTools(windows、linux);  Flexpaper插件(flexpaper_flash.js);
首先在电脑端安装好openofficeswftools软件,记住他们的安装位置(以windows下使用为例),安装位置路径最好不能有空格,最新版的openoffice对于各类office文档支持都较好。Java端使用openoffice需要几个jar包,可以通过maven下载或者直接把jar包引入项目:
jodconverter-core-3.0-alfresco-patched-20141024.jar(此jarmaven下载不了)
其他maven依赖:
<dependency>    <groupId>org.openoffice</groupId>    <artifactId>ridl</artifactId>    <version>4.1.2</version>    </dependency>    <dependency>    <groupId>org.openoffice</groupId>   <artifactId>unoil</artifactId>    <version>4.1.2</version>    </dependency>    <dependency>    <groupId>org.openoffice</groupId>    <artifactId>jurt</artifactId>    <version>4.1.2</version>    </dependency><dependency>    <groupId>org.openoffice</groupId>    <artifactId>juh</artifactId>    <version>4.1.2</version></dependency>


Java测试类:
 
package com.cdv.webview;import java.io.BufferedInputStream;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.util.regex.Pattern; import org.artofsolving.jodconverter.OfficeDocumentConverter;import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;import org.artofsolving.jodconverter.office.OfficeManager;import org.junit.Test; public class DocConverter {    @Test    public void test() {conver();    }     String filePath = "d:\\Users\\Administrator\\Desktop\\软件包\\symantec公开报价.xlsx";     String fileName = filePath.substring(0, filePath.lastIndexOf("."));     String outputPath = "f:\\";     int environment = 1;// 环境 1:Windows 2:Linux     File pdfFile = new File(fileName+ ".pdf");     File swfFile = new File(fileName+ ".swf");     File docFile = new File(filePath);        /**      * @Title: doc2pdf      * @Description: 文档转换为pdf文件    * @throws Exception    */    private void doc2pdf() throws Exception {     DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();                 String officeHome = getOfficeHome();          config.setOfficeHome(officeHome);                OfficeManager officeManager = config.buildOfficeManager();          officeManager.start();                OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);          if (docFile.exists()) {// 找不到源文件, 则返回              if (!pdfFile.getParentFile().exists()) { // 假如目标路径不存在, 则新建该路径               pdfFile.getParentFile().mkdirs();              }              converter.convert(docFile, pdfFile);          }                officeManager.stop();      }    /**      * @Title: getOfficeHome      * @Description: 根据不同系统获取openoffice安装路径    * @return String    */    public static String getOfficeHome() {          String osName = System.getProperty("os.name");          if (Pattern.matches("Linux.*", osName)) {              return "/opt/openoffice.org3";          } else if (Pattern.matches("Windows.*", osName)) {              return "C:\\Program Files (x86)\\OpenOffice 4";          } else if (Pattern.matches("Mac.*", osName)) {              return "/Application/OpenOffice.org.app/Contents";          }          return null;      }      /**      * @Title: pdf2swf      * @Description: pdf文件转换为swf文件    * @throws Exception    */    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:\\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已经存在不需要转换****");        }    }      /**      * @Title: loadStream      * @Description: 获取输出结果    * @param in    * @return String    * @throws IOException    */    public 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();    }      /**      * @Title: conver      * @Description: 文档转换为swf方法    * @return boolean    */    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()) {            System.out.println("****转换成功****");            return true;        } else {            System.out.println("****文件不存在,转换失败****");            return false;        }    }}
Jsp页面使用flexpaper_flash.js,主要的包结构,symantec.swf和test.swf为生成的swf测试文件,其他为flexpaper需要的文件。

<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%   String swfFilePath=new String("resources/test.swf");   System.out.println("展示路径:"+swfFilePath); %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta content="text/html;charset=UTF-8" http-equiv="Content-Type"><script type="text/javascript" src="js/jquery-1.11.1.min.js"></script><script type="text/javascript" src="js/flexpaper_flash.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:encodeURI('<%=swfFilePath%>'),Scale:1.2,            ZoomTransition:'easeOut',ZoomTime:0.5,ZoomInterval:0.2,FitPageOnLoad:false,FitWidthOnload:false,            FullScreenAsMaxWindow:false,ProgressiveLoading:false,MinZoomSize:0.2,MaxZoomSize:5,SearchMatchAll:false,            InitViewMode:'SinglePage',RenderingOrder : 'flash',ViewModeToolsVisible:true,ZoomToolsVisible:true,NavToolsVisible:true,CursorToolsVisible:true,            SearchToolsVisible:true,localeChain:'zh_CN'}});          </script>   </div></body></html>
启动tomcat可以查看此jsp得到预览效果。

所有用到的jar包、js下载地址请点击。
原创粉丝点击