天天看點

文檔線上預覽: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

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

進入windows任務管理器檢視有個程序soffice.bin,說明openoffice啟動成功!

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

(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檔案的播放器),目錄結構如下圖

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

(3)建立documentUpload.jsp檔案

[html]  view plain copy

  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. </head>  
  17. <body>  
  18. <div id="msg-box">  
  19.     <form name="form1"  method="post" enctype="multipart/form-data" action="docUploadConvertAction.jsp">  
  20.         <div class="title">  
  21.             請上傳要處理的檔案,過程可能需要幾分鐘,請稍候片刻。  
  22.         </div>  
  23.         <p>  
  24.             <input name="file1" type="file">  
  25.         </p>  
  26.         <p>  
  27.             <input type="submit" name="Submit" value="上傳">  
  28.         </p>  
  29.     </form >  
  30. </div>  
  31. </body>  
  32. </html>  

(4)建立文檔轉換類DocConverter.java

[java]  view plain copy

  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. import com.artofsolving.jodconverter.DocumentConverter;  
  7. import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;  
  8. import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;  
  9. import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;  
  10. public class DocConverter {  
  11.     private static final int environment = 1;// 環境 1:windows 2:linux  
  12.     private String fileString;// (隻涉及pdf2swf路徑問題)  
  13.     private String outputPath = "";// 輸入路徑 ,如果不設定就輸出在預設的位置  
  14.     private String fileName;  
  15.     private File pdfFile;  
  16.     private File swfFile;  
  17.     private File docFile;  
  18.     public DocConverter(String fileString) {  
  19.         ini(fileString);  
  20.     }  
  21.     public void setFile(String fileString) {  
  22.         ini(fileString);  
  23.     }  
  24.     private void ini(String fileString) {  
  25.         this.fileString = fileString;  
  26.         fileName = fileString.substring(0, fileString.lastIndexOf("."));  
  27.         docFile = new File(fileString);  
  28.         pdfFile = new File(fileName + ".pdf");  
  29.         swfFile = new File(fileName + ".swf");  
  30.     }  
  31.     private void doc2pdf() throws Exception {  
  32.         if (docFile.exists()) {  
  33.             if (!pdfFile.exists()) {  
  34.                 OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);  
  35.                 try {  
  36.                     connection.connect();  
  37.                     DocumentConverter converter = new OpenOfficeDocumentConverter(connection);  
  38.                     converter.convert(docFile, pdfFile);  
  39.                     // close the connection  
  40.                     connection.disconnect();  
  41.                     System.out.println("****pdf轉換成功,PDF輸出:" + pdfFile.getPath()+ "****");  
  42.                 } catch (java.net.ConnectException e) {  
  43.                     e.printStackTrace();  
  44.                     System.out.println("****swf轉換器異常,openoffice服務未啟動!****");  
  45.                     throw e;  
  46.                 } catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {  
  47.                     e.printStackTrace();  
  48.                     System.out.println("****swf轉換器異常,讀取轉換檔案失敗****");  
  49.                     throw e;  
  50.                 } catch (Exception e) {  
  51.                     e.printStackTrace();  
  52.                     throw e;  
  53.                 }  
  54.             } else {  
  55.                 System.out.println("****已經轉換為pdf,不需要再進行轉化****");  
  56.             }  
  57.         } else {  
  58.             System.out.println("****swf轉換器異常,需要轉換的文檔不存在,無法轉換****");  
  59.         }  
  60.     }  
  61.     @SuppressWarnings("unused")  
  62.     private void pdf2swf() throws Exception {  
  63.         Runtime r = Runtime.getRuntime();  
  64.         if (!swfFile.exists()) {  
  65.             if (pdfFile.exists()) {  
  66.                 if (environment == 1) {// windows環境處理  
  67.                     try {  
  68.                         Process p = r.exec("D:/Program Files/SWFTools/pdf2swf.exe "+ pdfFile.getPath() + " -o "+ swfFile.getPath() + " -T 9");  
  69.                         System.out.print(loadStream(p.getInputStream()));  
  70.                         System.err.print(loadStream(p.getErrorStream()));  
  71.                         System.out.print(loadStream(p.getInputStream()));  
  72.                         System.err.println("****swf轉換成功,檔案輸出:"  
  73.                                 + swfFile.getPath() + "****");  
  74.                         if (pdfFile.exists()) {  
  75.                             pdfFile.delete();  
  76.                         }  
  77.                     } catch (IOException e) {  
  78.                         e.printStackTrace();  
  79.                         throw e;  
  80.                     }  
  81.                 } else if (environment == 2) {// linux環境處理  
  82.                     try {  
  83.                         Process p = r.exec("pdf2swf " + pdfFile.getPath()  
  84.                                 + " -o " + swfFile.getPath() + " -T 9");  
  85.                         System.out.print(loadStream(p.getInputStream()));  
  86.                         System.err.print(loadStream(p.getErrorStream()));  
  87.                         System.err.println("****swf轉換成功,檔案輸出:"  
  88.                                 + swfFile.getPath() + "****");  
  89.                         if (pdfFile.exists()) {  
  90.                             pdfFile.delete();  
  91.                         }  
  92.                     } catch (Exception e) {  
  93.                         e.printStackTrace();  
  94.                         throw e;  
  95.                     }  
  96.                 }  
  97.             } else {  
  98.                 System.out.println("****pdf不存在,無法轉換****");  
  99.             }  
  100.         } else {  
  101.             System.out.println("****swf已經存在不需要轉換****");  
  102.         }  
  103.     }  
  104.     static String loadStream(InputStream in) throws IOException {  
  105.         int ptr = 0;  
  106.         in = new BufferedInputStream(in);  
  107.         StringBuffer buffer = new StringBuffer();  
  108.         while ((ptr = in.read()) != -1) {  
  109.             buffer.append((char) ptr);  
  110.         }  
  111.         return buffer.toString();  
  112.     }  
  113.     @SuppressWarnings("unused")  
  114.     public boolean conver() {  
  115.         if (swfFile.exists()) {  
  116.             System.out.println("****swf轉換器開始工作,該檔案已經轉換為swf****");  
  117.             return true;  
  118.         }  
  119.         if (environment == 1) {  
  120.             System.out.println("****swf轉換器開始工作,目前設定運作環境windows****");  
  121.         } else {  
  122.             System.out.println("****swf轉換器開始工作,目前設定運作環境linux****");  
  123.         }  
  124.         try {  
  125.             doc2pdf();  
  126.             pdf2swf();  
  127.         } catch (Exception e) {  
  128.             e.printStackTrace();  
  129.             return false;  
  130.         }  
  131.         if (swfFile.exists()) {  
  132.             return true;  
  133.         } else {  
  134.             return false;  
  135.         }  
  136.     }  
  137.     public String getswfPath() {  
  138.         if (swfFile.exists()) {  
  139.             String tempString = swfFile.getPath();  
  140.             tempString = tempString.replaceAll("\\\\", "/");  
  141.             return tempString;  
  142.         } else {  
  143.             return "";  
  144.         }  
  145.     }  
  146.     public void setOutputPath(String outputPath) {  
  147.         this.outputPath = outputPath;  
  148.         if (!outputPath.equals("")) {  
  149.             String realName = fileName.substring(fileName.lastIndexOf("/"),  
  150.                     fileName.lastIndexOf("."));  
  151.             if (outputPath.charAt(outputPath.length()) == '/') {  
  152.                 swfFile = new File(outputPath + realName + ".swf");  
  153.             } else {  
  154.                 swfFile = new File(outputPath + realName + ".swf");  
  155.             }  
  156.         }  
  157.     }  
  158. }  

(5)建立文檔上傳轉換處理檔案docUploadConvertAction.jsp檔案

[html]  view plain copy

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <%@page import="java.io.*"%>  
  4. <%@page import="java.util.Enumeration"%>  
  5. <%@page import="com.oreilly.servlet.MultipartRequest"%>  
  6. <%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>  
  7. <%@page import="com.cectsims.util.DocConverter"%>  
  8. <%  
  9. //檔案上傳采用cos元件上傳,可更換為commons-fileupload上傳,檔案上傳後,儲存在upload檔案夾  
  10. //擷取檔案上傳路徑  
  11. String saveDirectory =application.getRealPath("/")+"upload";  
  12. //列印上傳路徑資訊  
  13. System.out.println(saveDirectory);  
  14. //每個檔案最大50m  
  15. int maxPostSize = 50 * 1024 * 1024 ;  
  16. //采用cos預設的命名政策,重名後加1,2,3...如果不加dfp重名将覆寫  
  17. DefaultFileRenamePolicy dfp = new DefaultFileRenamePolicy();  
  18. //response的編碼為"UTF-8",同時采用預設的檔案名沖突解決政策,實作上傳,如果不加dfp重名将覆寫  
  19. MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize,"UTF-8",dfp);  
  20. //MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize,"UTF-8");  
  21. //輸出回報資訊  
  22.  Enumeration files = multi.getFileNames();  
  23.      while (files.hasMoreElements()) {  
  24.         System.err.println("ccc");  
  25.        String name = (String)files.nextElement();  
  26.        File f = multi.getFile(name);  
  27.        if(f!=null){  
  28.          String fileName = multi.getFilesystemName(name);  
  29.          //擷取上傳檔案的擴充名  
  30.          String extName=fileName.substring(fileName.lastIndexOf(".")+1);  
  31.          //檔案全路徑  
  32.          String lastFileName= saveDirectory+"\\" + fileName;  
  33.          //擷取需要轉換的檔案名,将路徑名中的'\'替換為'/'  
  34.          String converfilename = saveDirectory.replaceAll("\\\\", "/")+"/"+fileName;  
  35.          System.out.println(converfilename);  
  36.          //調用轉換類DocConverter,并将需要轉換的檔案傳遞給該類的構造方法  
  37.          DocConverter d = new DocConverter(converfilename);  
  38.          //調用conver方法開始轉換,先執行doc2pdf()将office檔案轉換為pdf;再執行pdf2swf()将pdf轉換為swf;  
  39.          d.conver();  
  40.          //調用getswfPath()方法,列印轉換後的swf檔案路徑  
  41.          System.out.println(d.getswfPath());  
  42.          //生成swf相對路徑,以便傳遞給flexpaper播放器  
  43.          String swfpath = "upload"+d.getswfPath().substring(d.getswfPath().lastIndexOf("/"));  
  44.          System.out.println(swfpath);  
  45.          //将相對路徑放入sessio中儲存  
  46.          session.setAttribute("swfpath", swfpath);  
  47.          out.println("上傳的檔案:"+lastFileName);  
  48.          out.println("檔案類型"+extName);  
  49.          out.println("<hr>");  
  50.        }  
  51.      }  
  52. %>  
  53. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  54. <html>  
  55. <head>  
  56. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  57. <title>Insert title here</title>  
  58. <style>  
  59.     body {margin-top:100px;background:#fff;font-family: Verdana, Tahoma;}  
  60.     a {color:#CE4614;}  
  61.     #msg-box {color: #CE4614; font-size:0.9em;text-align:center;}  
  62.     #msg-box .logo {border-bottom:5px solid #ECE5D9;margin-bottom:20px;padding-bottom:10px;}  
  63.     #msg-box .title {font-size:1.4em;font-weight:bold;margin:0 0 30px 0;}  
  64.     #msg-box .nav {margin-top:20px;}  
  65. </style>  
  66. </head>  
  67. <body>  
  68.     <div>  
  69.         <form name="viewForm" id="form_swf" action="documnetView.jsp" method="POST">  
  70.             <input type='submit' value='預覽' class='BUTTON SUBMIT'/>  
  71.         </form>  
  72.     </div>  
  73. </body>  
  74. </html>  

(6)建立文檔預覽檔案documentView.jsp

[html]  view plain copy

  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. <title>文檔線上預覽系統</title>  
  19. </head>  
  20. <body>   
  21.         <div style="position:absolute;left:50px;top:10px;">  
  22.             <a id="viewerPlaceHolder" style="width:820px;height:650px;display:block"></a>  
  23.             <script type="text/javascript">   
  24.                 var fp = new FlexPaperViewer(     
  25.                          'FlexPaperViewer',  
  26.                          'viewerPlaceHolder', { config : {  
  27.                          SwfFile : escape('<%=swfFilePath%>'),  
  28.                          Scale : 0.6,   
  29.                          ZoomTransition : 'easeOut',  
  30.                          ZoomTime : 0.5,  
  31.                          ZoomInterval : 0.2,  
  32.                          FitPageOnLoad : true,  
  33.                          FitWidthOnLoad : false,  
  34.                          FullScreenAsMaxWindow : false,  
  35.                          ProgressiveLoading : false,  
  36.                          MinZoomSize : 0.2,  
  37.                          MaxZoomSize : 5,  
  38.                          SearchMatchAll : false,  
  39.                          InitViewMode : 'SinglePage',  
  40.                          ViewModeToolsVisible : true,  
  41.                          ZoomToolsVisible : true,  
  42.                          NavToolsVisible : true,  
  43.                          CursorToolsVisible : true,  
  44.                          SearchToolsVisible : true,  
  45.                          localeChain: 'en_US'  
  46.                          }});  
  47.             </script>              
  48.         </div>  
  49. </body>  
  50. </html>  

7.啟動tomcat,部署目前web應用

8.位址欄輸入http://localhost:8080/ctcesims/documentUpload.jsp 如下圖:

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

單擊選擇檔案,選擇您要上傳的文檔,筆者選擇的是lunwen.doc檔案,然後單擊上傳,處理完成後,列印如下資訊,如下圖所示:

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

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

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

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

繼續閱讀