Office文件在线预览(JAVA)

 1、开发前准备

 1)下载第三方软件或插件进行安装

 openOffice:官方下载:http://www.openoffice.org/download/

                      百度网盘:http://pan.baidu.com/s/1mpxdL

 

      swftools:官方下载:http://www.swftools.org/swftools-0.9.0.exe

                      百度网盘:http://pan.baidu.com/s/11O0nS

 

FlexPaper_1.4.5_flash:http://pan.baidu.com/s/1oXmIL

 

Linux版本的安装及下载见:《openOffice、swftools安装指南(Linux).doc》

 

2)下载相关的jar包,如下图:


Office文件在线预览(JAVA)


 3)集成插件

解压FlexPaper_1.4.5_flash.zip,将以下文件移植到web目录下,如图


Office文件在线预览(JAVA)

 

 2、编写代码

 

项目源代码下载:http://pan.baidu.com/s/18AcnQ 

 

readfile.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<html>

  <head>

    <meta http-equiv="pragma" content="no-cache">

    <meta http-equiv="cache-control" content="no-cache">

    <meta http-equiv="expires" content="0">   

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

  </head>

  <body>

    <form action="uploadServlet" enctype="multipart/form-data" method="post">

        <font style="color:red">只支持office文件在线预览,如doc,docx,ppt,pptx,xls,xlxs</font></br>

        <input type="file" name="file"/></br>

        <input type="submit" value="在线预览">

    </form>

  </body>

</html>

 

UploadServlet.java 

package servlet;

import java.io.File;

import java.io.IOException;

import java.util.List;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileUploadException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import util.Office2Swf;

publicclass UploadServlet extends HttpServlet

{

    privatestaticfinallongserialVersionUID = 1L;

    @Override

    protectedvoid doGet(HttpServletRequest req, HttpServletResponse resp)

           throws ServletException, IOException

    {

       String inputFilePath = this.uploadFile(req);

       if (null != inputFilePath && !"".equals(inputFilePath.trim()))

       {

           String outFilePath = inputFilePath.replace(new File(inputFilePath).getName(), System.currentTimeMillis() + ".swf");

           outFilePath = Office2Swf.office2Swf(inputFilePath, outFilePath);

           req.getSession().setAttribute("fileName", new File(outFilePath).getName());

       }

       req.getRequestDispatcher("/readonline.jsp").forward(req, resp);

    }

   

    @Override

    protectedvoid doPost(HttpServletRequest req, HttpServletResponse resp)

           throws ServletException, IOException

    {

       this.doGet(req, resp);

    }

   

    @SuppressWarnings({"unchecked", "deprecation"})

    private String uploadFile(HttpServletRequest request)throws ServletException, IOException

    {

       request.setCharacterEncoding("utf-8");//设置编码

       //获得磁盘文件条目工厂

       DiskFileItemFactory factory = new DiskFileItemFactory();

       //获取文件需要上传到的路径

       String path = request.getRealPath("/upload");

       factory.setRepository(new File(path));

       //设置缓存的大小,当上传文件的容量超过该缓存时,直接放到暂时存储室

       factory.setSizeThreshold(1024*1024) ;

       //文件上传处理

       ServletFileUpload upload = new ServletFileUpload(factory);

      

       String uploadFilePath = null;

       //可以上传多个文件

       try {

           List<FileItem> list = (List<FileItem>)upload.parseRequest(request);

           for(FileItem item : list)

           {

              //获取表单的属性名字

              String name = item.getFieldName();

             

              // 表单文本信息

              if(item.isFormField())

              {                

                  String value = item.getString() ;

                  request.setAttribute(name, value);

              }

              // 表单上传的文件

              else

              {

                  // 获取路径

                  String value = item.getName() ;

                  int start = value.lastIndexOf("\\");

                  // 截取上传文件名称

                  String filename = value.substring(start+1);

                  request.setAttribute(name, filename);

                  item.write(new File(path,filename));

                  uploadFilePath = path + File.separator + filename;

              }

           }

       } catch (FileUploadException e) {

           e.printStackTrace();

       }

       catch(Exception ex)

       {

           ex.printStackTrace();

       }

       return uploadFilePath;

    }

}

 

Office2PDF.java

package util;

 

import java.io.File;

import java.util.ArrayList;

import java.util.Collections;

import java.util.regex.Pattern;

 

import org.artofsolving.jodconverter.OfficeDocumentConverter;

import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;

import org.artofsolving.jodconverter.office.OfficeManager;

 

/**

 *

 * @author hwl_sz

 *

 * @desc需要OpenOffice第三插件的支持 ,支持window\linux\mac等系统

 */

publicclass Office2PDF

{

    publicstaticfinal String[] OFFICE_POSTFIXS = {"doc", "docx", "xls",

       "xlsx", "ppt", "pptx"};

   

    /**

     * 根据操作系统的名称,获取OpenOffice的安装目录

     * 如我的安装目录:C:/Program Files/OpenOffice 4

     */

    privatestatic String getOfficeHome()

    {

       String osName = System.getProperty("os.name");

       if (Pattern.matches("Linux.*", osName))

       {

           return"/opt/openoffice.org3";

       }

       elseif (Pattern.matches("Windows.*", osName))

       {

           return"C:/Program Files/OpenOffice 4";

       }

       elseif (Pattern.matches("Mac.*", osName))

       {

           return"/Application/OpenOffice.org.app/Contents";

       }

       returnnull;

    }

 

    /**

     * 转换文件

     *

     * @param inputFilePath 转换的office源文件路径

     * @param outputFilePath 输出目标文件路径

     */

    privatestaticvoid converterFile(String inputFilePath, String outputFilePath)

    {

       File inputFile = new File(inputFilePath);

       File outputFile = new File(outputFilePath);

       // 假如目标路径不存在,则新建该路径

       if (!outputFile.getParentFile().exists())

       {

           outputFile.getParentFile().mkdirs();

       }

      

       DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();

       // 获取OpenOffice 的安装目录

       String officeHome = getOfficeHome();

       config.setOfficeHome(officeHome);

       // 启动OpenOffice的服务

       OfficeManager officeManager = config.buildOfficeManager();

       officeManager.start();

      

       OfficeDocumentConverter converter = new OfficeDocumentConverter(

              officeManager);

      

       converter.convert(inputFile, outputFile);

       System.out.println("文件:" + inputFilePath + "\n转换为\n目标文件:" + outputFile

              + "\n成功!");

      

       officeManager.stop();

    }

 

    /**

     * (.doc|.docx|.xls|.xlsx|.ppt|.pptx)office文件转化为pdf文件

     *

     * @param inputFilePath 待转换的源文件路径

     * @param outputFilePath 输出的目录文件路径,如果未指定(null),则按在源文件当前目录生成同名的pdf文件

     * @return处理结果

     */

    publicstaticboolean openOffice2Pdf(String inputFilePath, String outputFilePath)

    {

       boolean flag = false;

       File inputFile = new File(inputFilePath);

       ArrayList<String> office_Formats = new ArrayList<String>();

       Collections.addAll(office_Formats, OFFICE_POSTFIXS);

       if ((null != inputFilePath) && (inputFile.exists()))

       {

           // 判断目标文件路径是否为空

           if (office_Formats.contains(getPostfix(inputFilePath)))

           {

              if (null == outputFilePath)

              {

                  // 转换后的文件路径

                  String outputFilePath_new = inputFilePath.toLowerCase().replaceAll("."

                         + getPostfix(inputFilePath), ".pdf");

                  converterFile(inputFilePath, outputFilePath_new);

                  flag = true;

              }

              else

              {

                  converterFile(inputFilePath, outputFilePath);

                  flag = true;

              }

           }

       }

       return flag;

    }

 

 

    /**

     * 获取文件的后缀名

     */

    privatestatic String getPostfix(String inputFilePath)

    {

       String[] p = inputFilePath.split("\\.");

       if (p.length > 0)

       {

           return p[p.length - 1];

       }

        else

       {

           returnnull;

       }

    }

 

    /**

     * @param args

     */

    publicstaticvoid main(String[] args)

    {

       Office2PDF.openOffice2Pdf("E:/黄色地球商务PPT模板.ppt",null);

    }

}

 

 

Office2Swf.java

package util;

 

import java.util.regex.Pattern;

 

/**

 *

 * @author hwl_sz

 *

 * @desc需要swftools第三插件的支持 ,支持window\linux\mac等系统

 */

publicclass Office2Swf

{

    /**

     * 根据操作系统的名称,获取执行pdf->swf文件的命令

     * @param pdfFile 转换的pdf源文件路径

     * @param swfOutFilePath 输出的swf文件路径

     * @return

     */

    privatestatic String getCommand(String pdfFile, String swfOutFilePath)

    {

       String command = null;

       String osName = System.getProperty("os.name");

       if (null == swfOutFilePath || "".equals(swfOutFilePath.trim()))

       {

           swfOutFilePath = pdfFile.toLowerCase().replaceAll(".pdf", ".swf");

       }

      

       if (Pattern.matches("Linux.*", osName))

       {

           command = "pdf2swf -f " + pdfFile + " " + swfOutFilePath;

       }

       elseif (Pattern.matches("Windows.*", osName))

       {

           command = "C:/Program Files/SWFTools/pdf2swf.exe -t " + pdfFile + " -o "  + swfOutFilePath + " -T 9";

       }

       elseif (Pattern.matches("Mac.*", osName))

       {

       }

       return command;

    }

   

    /**

     * pdf转换swf文件,在线预览

     * @param pdfInputFilePath 待转换的pdf源文件路径

     * @param swfOutFilePath  输出的swf目标文件路径,如果未指定(null),则按在源文件当前目录生成同名的swf文件

     * @return swf目标文件路径

     */

    publicstatic String pdf2Swf(String pdfInputFilePath, String swfOutFilePath)

    {

       String command = getCommand(pdfInputFilePath, swfOutFilePath);

       try

       {

           Process pro = Runtime.getRuntime().exec(command);

           pro.waitFor();

           return pdfInputFilePath.replaceAll("." + getPostfix(pdfInputFilePath), ".swf");

       }

       catch(Exception ex)

       {

           ex.printStackTrace();

       }

       returnnull;

    }

   

    /**

     * office文件直接转换为swf文件

     * @param inputFilePath 待转换的源office文件路径

     * @param outputSwfPath 输出的swf目标文件路径,如果未指定(null),则按在源文件当前目录生成同名的swf文件

     * @return swf目标文件路径

     */

    publicstatic String office2Swf(String inputFilePath, String outputSwfPath)

    {

       String outputPdfPath = null;

       if (null == outputSwfPath || "".equals(outputSwfPath.trim()))

       {

           outputPdfPath = inputFilePath.replace("." + getPostfix(inputFilePath), ".pdf");

       }

       else

       {

           outputPdfPath = outputSwfPath.replace("." + getPostfix(outputSwfPath), ".pdf");

       }

      

       boolean isSucc = Office2PDF.openOffice2Pdf(inputFilePath, outputPdfPath);

       if (isSucc)

       {

           outputSwfPath = pdf2Swf(outputPdfPath, outputSwfPath);

       }

       return outputSwfPath;

    }

   

    /**

     * 获取文件的后缀名

     */

    privatestatic String getPostfix(String inputFilePath)

    {

       String postfix = null;

       if (null != inputFilePath && !"".equals(inputFilePath.trim()))

       {

           int idx = inputFilePath.lastIndexOf(".");

           if (idx > 0)

           {

              postfix = inputFilePath.substring(idx + 1, inputFilePath.trim().length());

           }

       }

       return postfix;

    }

}

 

readonline.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">  

  <head>

    <title>在线预览</title>

<script type="text/javascript" src="FlexPaper/js/jquery.js"></script>

<script type="text/javascript" src="FlexPaper/js/flexpaper_flash.js"></script>

<script type="text/javascript" src="FlexPaper/js/flexpaper_flash_debug.js"></script>

  </head>

  <%--  <%=(String)session.getAttribute("fileName")%>  --%>

  <body>

        <div style="position:absolute;left:10px;top:10px;">

        <%-- 指定flexPaper的宽度和高度  --%>  

            <a id="viewerPlaceHolder" style="width:100%;height:800px;display:block"></a> 

            <script type="text/javascript">

                var fp = new FlexPaperViewer(   

                         'FlexPaper/swfFiles/FlexPaperViewer',

                         'viewerPlaceHolder',     <!--对应于a 标签的id-->

                         { config : {

                         SwfFile : escape('upload/<%=(String)session.getAttribute("fileName")%>'),  <!--导入的.swf的路径,文件名称使用英语表示,中文时显示不出来,暂时未解决这个问题-->

                         Scale : 0.6,

                         ZoomTransition : 'easeOut',

                         ZoomTime : 0.5,

                         ZoomInterval : 0.2,

                         FitPageOnLoad : true,

                         FitWidthOnLoad : false,

                         PrintEnabled : true,<%-- 是否可以打印  --%>

                         FullScreenAsMaxWindow : false,

                         ProgressiveLoading : false,

                         MinZoomSize : 0.2,

                         MaxZoomSize : 5,

                         SearchMatchAll : false,

                         InitViewMode : 'Portrait',

                        

                         ViewModeToolsVisible : true,

                         ZoomToolsVisible : true,

                         NavToolsVisible : true,

                         CursorToolsVisible : true,

                         SearchToolsVisible : true,

                           localeChain: 'en_US'

                         }});

            </script>

        </div>

</body>

</html>

 

效果图 


Office文件在线预览(JAVA)
 

 

你可能感兴趣的:(word,xls,ppt,在线预览,预览)