文檔在線預覽:Java+FlexPaper+swfTools仿百度文庫的設計與實現

筆者最近在給客戶開發文檔管理系統時,客戶要求上傳到管理系統的文檔(包括ppt,word,excel,txt)只能預覽不允許下載。筆者想到了百度文庫和豆丁網,百度文庫和豆丁網的在線預覽都是利用flash來播放文檔的,在網上查閱了大量資料,終於實現了該項功能,現將自己的設計和實現整理如下。

一、如何將文檔轉成flash支持的swf文件實現在線播放?
1.先用openOffice把ppt、word、excel、txt類型的文檔轉換成pdf
2.用swftools將pdf轉換成swf,然後利用FlexPaper插件實現在線播放預覽。
二、具體實現
1.安裝必備工具組件
(1)安裝openoffice,openoffice是開源免費的文字處理軟件,它可以將office文檔轉成pdf文件(筆者安裝到D:\Program Files),openOffice下載地址http://www.openoffice.org/download/index.html
(2)安裝完openoffice後必須啓動其server,以命令行方式啓動openoffice server。進入cmd命令行提示符D:\Program Files\OpenOffice.org 3\program\
鍵入如下命令:
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" –nofirststartwizard

進入windows任務管理器查看有個進程soffice.bin,說明openoffice啓動成功!

(3)安裝swfTools(安裝到 D:\Program Files)swftools作用是將pdf轉換爲swf文件以便flexpaper播放。下載地址:http://www.swftools.org/download.html
(4)下載flexpaper,下載地址:http://flexpaper.devaldi.com/download/
筆者下載的是FlexPaper_1.5.1,下載後將其解壓備用。
(5)下載OpenDocument文檔轉換器 JODConverter,JODConverter是一個java的OpenDucument文件轉換器,可以進行許多文件格式的轉換,它利用OpenOffice來進行轉換工作,它能進行以下的轉換工作:
a.Microsoft Office格式轉換爲OpenDucument,以及OpenDucument轉換爲Microsoft Office
b.OpenDucument轉換爲PDF,Word、Excel、PowerPoint轉換爲PDF,RTF轉換爲PDF等。
下載地址:http://sourceforge.net/projects/jodconverter/files/
我們後面開發主要用它的jodconverter-2.2.2.jar包

2.軟件開發過程
(1)啓動Eclipse,新建web項目名稱爲ctcesims
(2)將上面第4步解壓的flexpaper文件中的js文件夾(包含了flexpaper_flash_debug.js,flexpaper_flash.js,jquery.js,這三個js文件主要是預覽swf文件的插件)拷貝至網站根目錄;將FlexPaperViewer.swf拷貝至網站根目錄下(該文件主要是用在網頁中播放swf文件的播放器),目錄結構如下圖

(3)創建documentUpload.jsp文件
[html] view plaincopy
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  7. <title>文檔在線預覽系統</title>  
  8. <style>  
  9.     body {margin-top:100px;background:#fff;font-family: Verdana, Tahoma;}  
  10.     a {color:#CE4614;}  
  11.     #msg-box {color: #CE4614; font-size:0.9em;text-align:center;}  
  12.     #msg-box .logo {border-bottom:5px solid #ECE5D9;margin-bottom:20px;padding-bottom:10px;}  
  13.     #msg-box .title {font-size:1.4em;font-weight:bold;margin:0 0 30px 0;}  
  14.     #msg-box .nav {margin-top:20px;}  
  15. </style>  
  16.   
  17. </head>  
  18. <body>  
  19. <div id="msg-box">  
  20.     <form name="form1"  method="post" enctype="multipart/form-data" action="docUploadConvertAction.jsp">  
  21.         <div class="title">  
  22.             請上傳要處理的文件,過程可能需要幾分鐘,請稍候片刻。  
  23.         </div>  
  24.         <p>  
  25.             <input name="file1" type="file">  
  26.         </p>  
  27.         <p>  
  28.             <input type="submit" name="Submit" value="上傳">  
  29.         </p>  
  30.     </form >  
  31. </div>  
  32. </body>  
  33. </html>  
(4)創建文檔轉換類DocConverter.java
[java] view plaincopy
  1. package com.cectsims.util;  
  2. import java.io.BufferedInputStream;  
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6.   
  7. import com.artofsolving.jodconverter.DocumentConverter;  
  8. import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;  
  9. import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;  
  10. import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;  
  11.   
  12. /** 
  13.  * doc docx格式轉換 
  14.  */  
  15. public class DocConverter {  
  16.     private static final int environment = 1;// 環境 1:windows 2:linux  
  17.     private String fileString;// (只涉及pdf2swf路徑問題)  
  18.     private String outputPath = "";// 輸入路徑 ,如果不設置就輸出在默認的位置  
  19.     private String fileName;  
  20.     private File pdfFile;  
  21.     private File swfFile;  
  22.     private File docFile;  
  23.       
  24.     public DocConverter(String fileString) {  
  25.         ini(fileString);  
  26.     }  
  27.   
  28.     /** 
  29.      * 重新設置file 
  30.      *  
  31.      * @param fileString 
  32.      */  
  33.     public void setFile(String fileString) {  
  34.         ini(fileString);  
  35.     }  
  36.   
  37.     /** 
  38.      * 初始化 
  39.      *  
  40.      * @param fileString 
  41.      */  
  42.     private void ini(String fileString) {  
  43.         this.fileString = fileString;  
  44.         fileName = fileString.substring(0, fileString.lastIndexOf("."));  
  45.         docFile = new File(fileString);  
  46.         pdfFile = new File(fileName + ".pdf");  
  47.         swfFile = new File(fileName + ".swf");  
  48.     }  
  49.       
  50.     /** 
  51.      * 轉爲PDF 
  52.      *  
  53.      * @param file 
  54.      */  
  55.     private void doc2pdf() throws Exception {  
  56.         if (docFile.exists()) {  
  57.             if (!pdfFile.exists()) {  
  58.                 OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);  
  59.                 try {  
  60.                     connection.connect();  
  61.                     DocumentConverter converter = new OpenOfficeDocumentConverter(connection);  
  62.                     converter.convert(docFile, pdfFile);  
  63.                     // close the connection  
  64.                     connection.disconnect();  
  65.                     System.out.println("****pdf轉換成功,PDF輸出:" + pdfFile.getPath()+ "****");  
  66.                 } catch (java.net.ConnectException e) {  
  67.                     e.printStackTrace();  
  68.                     System.out.println("****swf轉換器異常,openoffice服務未啓動!****");  
  69.                     throw e;  
  70.                 } catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {  
  71.                     e.printStackTrace();  
  72.                     System.out.println("****swf轉換器異常,讀取轉換文件失敗****");  
  73.                     throw e;  
  74.                 } catch (Exception e) {  
  75.                     e.printStackTrace();  
  76.                     throw e;  
  77.                 }  
  78.             } else {  
  79.                 System.out.println("****已經轉換爲pdf,不需要再進行轉化****");  
  80.             }  
  81.         } else {  
  82.             System.out.println("****swf轉換器異常,需要轉換的文檔不存在,無法轉換****");  
  83.         }  
  84.     }  
  85.       
  86.     /** 
  87.      * 轉換成 swf 
  88.      */  
  89.     @SuppressWarnings("unused")  
  90.     private void pdf2swf() throws Exception {  
  91.         Runtime r = Runtime.getRuntime();  
  92.         if (!swfFile.exists()) {  
  93.             if (pdfFile.exists()) {  
  94.                 if (environment == 1) {// windows環境處理  
  95.                     try {  
  96.                         Process p = r.exec("D:/Program Files/SWFTools/pdf2swf.exe "+ pdfFile.getPath() + " -o "+ swfFile.getPath() + " -T 9");  
  97.                         System.out.print(loadStream(p.getInputStream()));  
  98.                         System.err.print(loadStream(p.getErrorStream()));  
  99.                         System.out.print(loadStream(p.getInputStream()));  
  100.                         System.err.println("****swf轉換成功,文件輸出:"  
  101.                                 + swfFile.getPath() + "****");  
  102.                         if (pdfFile.exists()) {  
  103.                             pdfFile.delete();  
  104.                         }  
  105.   
  106.                     } catch (IOException e) {  
  107.                         e.printStackTrace();  
  108.                         throw e;  
  109.                     }  
  110.                 } else if (environment == 2) {// linux環境處理  
  111.                     try {  
  112.                         Process p = r.exec("pdf2swf " + pdfFile.getPath()  
  113.                                 + " -o " + swfFile.getPath() + " -T 9");  
  114.                         System.out.print(loadStream(p.getInputStream()));  
  115.                         System.err.print(loadStream(p.getErrorStream()));  
  116.                         System.err.println("****swf轉換成功,文件輸出:"  
  117.                                 + swfFile.getPath() + "****");  
  118.                         if (pdfFile.exists()) {  
  119.                             pdfFile.delete();  
  120.                         }  
  121.                     } catch (Exception e) {  
  122.                         e.printStackTrace();  
  123.                         throw e;  
  124.                     }  
  125.                 }  
  126.             } else {  
  127.                 System.out.println("****pdf不存在,無法轉換****");  
  128.             }  
  129.         } else {  
  130.             System.out.println("****swf已經存在不需要轉換****");  
  131.         }  
  132.     }  
  133.   
  134.     static String loadStream(InputStream in) throws IOException {  
  135.   
  136.         int ptr = 0;  
  137.         in = new BufferedInputStream(in);  
  138.         StringBuffer buffer = new StringBuffer();  
  139.   
  140.         while ((ptr = in.read()) != -1) {  
  141.             buffer.append((char) ptr);  
  142.         }  
  143.   
  144.         return buffer.toString();  
  145.     }  
  146.     /** 
  147.      * 轉換主方法 
  148.      */  
  149.     @SuppressWarnings("unused")  
  150.     public boolean conver() {  
  151.   
  152.         if (swfFile.exists()) {  
  153.             System.out.println("****swf轉換器開始工作,該文件已經轉換爲swf****");  
  154.             return true;  
  155.         }  
  156.   
  157.         if (environment == 1) {  
  158.             System.out.println("****swf轉換器開始工作,當前設置運行環境windows****");  
  159.         } else {  
  160.             System.out.println("****swf轉換器開始工作,當前設置運行環境linux****");  
  161.         }  
  162.         try {  
  163.             doc2pdf();  
  164.             pdf2swf();  
  165.         } catch (Exception e) {  
  166.             e.printStackTrace();  
  167.             return false;  
  168.         }  
  169.   
  170.         if (swfFile.exists()) {  
  171.             return true;  
  172.         } else {  
  173.             return false;  
  174.         }  
  175.     }  
  176.   
  177.     /** 
  178.      * 返回文件路徑 
  179.      *  
  180.      * @param s 
  181.      */  
  182.     public String getswfPath() {  
  183.         if (swfFile.exists()) {  
  184.             String tempString = swfFile.getPath();  
  185.             tempString = tempString.replaceAll("\\\\", "/");  
  186.             return tempString;  
  187.         } else {  
  188.             return "";  
  189.         }  
  190.   
  191.     }  
  192.     /** 
  193.      * 設置輸出路徑 
  194.      */  
  195.     public void setOutputPath(String outputPath) {  
  196.         this.outputPath = outputPath;  
  197.         if (!outputPath.equals("")) {  
  198.             String realName = fileName.substring(fileName.lastIndexOf("/"),  
  199.                     fileName.lastIndexOf("."));  
  200.             if (outputPath.charAt(outputPath.length()) == '/') {  
  201.                 swfFile = new File(outputPath + realName + ".swf");  
  202.             } else {  
  203.                 swfFile = new File(outputPath + realName + ".swf");  
  204.             }  
  205.         }  
  206.     }  
  207.   
  208. }  
(5)創建文檔上傳轉換處理文件docUploadConvertAction.jsp文件
[html] view plaincopy
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3.   
  4. <%@page import="java.io.*"%>  
  5. <%@page import="java.util.Enumeration"%>  
  6. <%@page import="com.oreilly.servlet.MultipartRequest"%>  
  7. <%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>  
  8. <%@page import="com.cectsims.util.DocConverter"%>  
  9. <%  
  10. //文件上傳採用cos組件上傳,可更換爲commons-fileupload上傳,文件上傳後,保存在upload文件夾  
  11. //獲取文件上傳路徑  
  12. String saveDirectory =application.getRealPath("/")+"upload";  
  13. //打印上傳路徑信息  
  14. System.out.println(saveDirectory);  
  15. //每個文件最大50m  
  16. int maxPostSize = 50 * 1024 * 1024 ;  
  17. //採用cos缺省的命名策略,重名後加1,2,3...如果不加dfp重名將覆蓋  
  18. DefaultFileRenamePolicy dfp = new DefaultFileRenamePolicy();  
  19. //response的編碼爲"UTF-8",同時採用缺省的文件名衝突解決策略,實現上傳,如果不加dfp重名將覆蓋  
  20. MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize,"UTF-8",dfp);  
  21. //MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize,"UTF-8");  
  22. //輸出反饋信息  
  23.  Enumeration files = multi.getFileNames();  
  24.      while (files.hasMoreElements()) {  
  25.         System.err.println("ccc");  
  26.        String name = (String)files.nextElement();  
  27.        File f = multi.getFile(name);  
  28.        if(f!=null){  
  29.          String fileName = multi.getFilesystemName(name);  
  30.          //獲取上傳文件的擴展名  
  31.          String extName=fileName.substring(fileName.lastIndexOf(".")+1);  
  32.          //文件全路徑  
  33.          String lastFileNamesaveDirectory+"\\" + fileName;  
  34.          //獲取需要轉換的文件名,將路徑名中的'\'替換爲'/'  
  35.          String converfilename = saveDirectory.replaceAll("\\\\", "/")+"/"+fileName;  
  36.          System.out.println(converfilename);  
  37.          //調用轉換類DocConverter,並將需要轉換的文件傳遞給該類的構造方法  
  38.          DocConverter d = new DocConverter(converfilename);  
  39.          //調用conver方法開始轉換,先執行doc2pdf()將office文件轉換爲pdf;再執行pdf2swf()將pdf轉換爲swf;  
  40.          d.conver();  
  41.          //調用getswfPath()方法,打印轉換後的swf文件路徑  
  42.          System.out.println(d.getswfPath());  
  43.          //生成swf相對路徑,以便傳遞給flexpaper播放器  
  44.          String swfpath = "upload"+d.getswfPath().substring(d.getswfPath().lastIndexOf("/"));  
  45.          System.out.println(swfpath);  
  46.          //將相對路徑放入sessio中保存  
  47.          session.setAttribute("swfpath", swfpath);  
  48.          out.println("上傳的文件:"+lastFileName);  
  49.          out.println("文件類型"+extName);  
  50.          out.println("<hr>");  
  51.        }  
  52.      }  
  53.   
  54. %>  
  55. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  56. <html>  
  57. <head>  
  58. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  59. <title>Insert title here</title>  
  60. <style>  
  61.     body {margin-top:100px;background:#fff;font-family: Verdana, Tahoma;}  
  62.     a {color:#CE4614;}  
  63.     #msg-box {color: #CE4614; font-size:0.9em;text-align:center;}  
  64.     #msg-box .logo {border-bottom:5px solid #ECE5D9;margin-bottom:20px;padding-bottom:10px;}  
  65.     #msg-box .title {font-size:1.4em;font-weight:bold;margin:0 0 30px 0;}  
  66.     #msg-box .nav {margin-top:20px;}  
  67. </style>  
  68. </head>  
  69. <body>  
  70.     <div>  
  71.         <form name="viewForm" id="form_swf" action="documnetView.jsp" method="POST">  
  72.             <input type='submit' value='預覽' class='BUTTON SUBMIT'/>  
  73.         </form>  
  74.     </div>  
  75. </body>  
  76. </html>  
(6)創建文檔預覽文件documentView.jsp
[html] view plaincopy
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <%  
  4.     String swfFilePath=session.getAttribute("swfpath").toString();  
  5. %>  
  6. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  7. <html>  
  8. <head>  
  9. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  10. <script type="text/javascript" src="js/jquery.js"></script>  
  11. <script type="text/javascript" src="js/flexpaper_flash.js"></script>  
  12. <script type="text/javascript" src="js/flexpaper_flash_debug.js"></script>  
  13. <style type="text/css" media="screen">   
  14.             html, body  { height:100%; }  
  15.             body { margin:0; padding:0; overflow:auto; }     
  16.             #flashContent { display:none; }  
  17.         </style>   
  18.   
  19. <title>文檔在線預覽系統</title>  
  20. </head>  
  21. <body>   
  22.         <div style="position:absolute;left:50px;top:10px;">  
  23.             <a id="viewerPlaceHolder" style="width:820px;height:650px;display:block"></a>  
  24.               
  25.             <script type="text/javascript">   
  26.                 var fp = new FlexPaperViewer(     
  27.                          'FlexPaperViewer',  
  28.                          'viewerPlaceHolder', { config : {  
  29.                          SwfFile : escape('<%=swfFilePath%>'),  
  30.                          Scale : 0.6,   
  31.                          ZoomTransition : 'easeOut',  
  32.                          ZoomTime : 0.5,  
  33.                          ZoomInterval : 0.2,  
  34.                          FitPageOnLoad : true,  
  35.                          FitWidthOnLoad : false,  
  36.                          FullScreenAsMaxWindow : false,  
  37.                          ProgressiveLoading : false,  
  38.                          MinZoomSize : 0.2,  
  39.                          MaxZoomSize : 5,  
  40.                          SearchMatchAll : false,  
  41.                          InitViewMode : 'SinglePage',  
  42.                            
  43.                          ViewModeToolsVisible : true,  
  44.                          ZoomToolsVisible : true,  
  45.                          NavToolsVisible : true,  
  46.                          CursorToolsVisible : true,  
  47.                          SearchToolsVisible : true,  
  48.                           
  49.                          localeChain: 'en_US'  
  50.                          }});  
  51.             </script>              
  52.         </div>  
  53. </body>  
  54. </html>  
7.啓動tomcat,部署當前web應用
8.地址欄輸入http://localhost:8080/ctcesims/documentUpload.jsp 如下圖:


單擊選擇文件,選擇您要上傳的文檔,筆者選擇的是lunwen.doc文件,然後單擊上傳,處理完成後,打印如下信息,如下圖所示:

單擊預覽按鈕,就會生成預覽界面,如下圖:

9.若出現swf無法預覽,請訪問
http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04a.html#119065將生成swf的文件夾設置爲信任文件位置。
由於時間倉促,以上只是簡單示例,很多情況還需要進一步考慮!

參考資料:
http://blog.csdn.net/iamduoluo/article/details/6727031
http://www.cnblogs.com/star-studio/archive/2011/12/09/2282411.html#2497889

發佈了4 篇原創文章 · 獲贊 11 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章