Java模擬實現百度文檔在線瀏覽

Java模擬實現百度文檔在線瀏覽

這個思路是我參考網上而來,代碼是我實現。javascript

採用Apache下面的OpenOffice將資源文件轉化爲pdf文件,而後將pdf文件轉化爲swf文件,用FlexPaper瀏覽。css

ok,html

A、下載OpenOffice (轉換資源文件)java

B、下載JodConverter(調用OpenOffice)linux

C、下載Swftools(Pdf2Swf)web

D、下載 FlexPaper(瀏覽swf文件)服務器

這裏我已經所有下載好了,你們只須要下載: http://down.51cto.com/data/1980603session

下載以後,先別急安裝,請看完這篇博文app

一、先看咱們的MyEclipse工程結構less

二、

將咱們下載下來的  解壓以後將全部的 jar 文件拷貝到 baiduDoc 的 lib 下面去

三、   在 WebRoot 下面新建  文件夾,將解壓後的  所有拷貝到 FlexPaper中去

四、 新建BaiDuServlet.java文件

package com.baidu.util;import java.io.BufferedInputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.net.ConnectException;import javax.p_w_picpathio.stream.FileImageInputStream;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;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;/**
 * @Author:NuoYan
 * @Date:2015-2-2 下午2:24:58 
 * TODO: 一、第一步,首先獲取到須要查看的文件
 *       二、第二部,將獲取的文件(doc,xls,txt,ppt,03/07版本轉化爲PDF),這一步須要調用OpenOffice
 *       三、第三部,將資源文件轉換好的PDF文件轉換爲swf文件,使用FlexPaperViewer.swf進行瀏覽查看
 */public class BaiDuServlet extends HttpServlet {  private File sourceFile;// 要轉化的源文件  private File pdfFile;// pdf中間文件對象  private File swfFile;// swf目標文件對象  private String filePath;// 用來保存文件路徑  private String fileName;// 不包括後綴名的文件名  public File getSourceFile() {    return sourceFile;  }  public void setSourceFile(File sourceFile) {    this.sourceFile = sourceFile;  }  public File getPdfFile() {    return pdfFile;  }  public void setPdfFile(File pdfFile) {    this.pdfFile = pdfFile;  }  public File getSwfFile() {    return swfFile;  }  public void setSwfFile(File swfFile) {    this.swfFile = swfFile;  }  public String getFilePath() {    return filePath;  }  public void setFilePath(String filePath) {    this.filePath = filePath;  }  public String getFileName() {    return fileName;  }  public void setFileName(String fileName) {    this.fileName = fileName;  }  public void doGet(HttpServletRequest request, HttpServletResponse response)      throws ServletException, IOException {    String saveFileName = request.getParameter("savFile");    System.out.println(saveFileName);    String webPath = request.getRealPath("/");    filePath = webPath + "reader\\" + saveFileName;    fileName = filePath.substring(0, filePath.lastIndexOf("."));    // 建立三個文件對象    sourceFile = new File(filePath);    pdfFile = new File(fileName + ".pdf");    swfFile = new File(fileName + ".swf");    System.out.println(pdfFile);    System.out.println(swfFile);    // 一、將源文件轉化爲pdf格式文件    src2pdf();    try {      // 二、將pdf文件轉化爲swf文件      pdf2swf();    } catch (Exception e) {      e.printStackTrace();    }    // 將轉化好的文件綁定到session上去    request.getSession().setAttribute("swfName", swfFile.getName());    System.out.println(swfFile.getName());    // 重定向到預覽頁面    response.sendRedirect(request.getContextPath() + "/reader/baseFile.jsp");  }  /**   * @Author:NuoYan   * @Date:2015-2-2 下午2:28:22 TODO://源文件轉化爲PDF文件   */  private void src2pdf() {    if (sourceFile.exists()) {      // 若是不存在,須要轉份爲PDF文件      if (!pdfFile.exists()) {        // 啓用OpenOffice提供的轉化服務        OpenOfficeConnection conn = new SocketOpenOfficeConnection(8100);        // 鏈接OpenOffice服務器        try {          conn.connect();          // 創建文件轉換器對象          DocumentConverter converter = new OpenOfficeDocumentConverter(              conn);          converter.convert(sourceFile, pdfFile);          // 斷開連接          conn.disconnect();          System.out.println("轉換成功");        } catch (ConnectException e) {          e.printStackTrace();        }      } else {        System.out.println("已經存在PDF文件,不須要在轉換!!");      }    } else {      System.out.println("文件路徑不存在!!!");    }  }  /**   * @Author:NuoYan   * @Date:2015-2-2 下午2:28:32   * @throws Exception   * TODO:PDF轉化爲SWF文件   */  private void pdf2swf() throws Exception {    if (!swfFile.exists()) {      if (pdfFile.exists()) {        String command = "C:\\Pdf2swf\\pdf2swf.exe "            + pdfFile.getPath() + " -o " + swfFile.getPath()            + " -T 9";        System.out.println("轉換命令:" + command);        // Java調用外部命令,執行pdf轉化爲swf        Runtime r = Runtime.getRuntime();        Process p = r.exec(command);        System.out.println(loadStream(p.getInputStream()));        System.out.println("swf文件轉份成功!!!");        System.out.println(swfFile.getPath());      } else {        System.out.println("不存在PDF文件");      }    }  }    private static String loadStream(InputStream in) throws Exception {    int len = 0;    in = new BufferedInputStream(in);    StringBuffer buffer = new StringBuffer();    while ((len = in.read()) != -1) {      buffer.append((char) len);    }    return buffer.toString();  }

}

五、 修改index.jsp

<%@ page language="java" import="java.util.*"pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>百度文庫在線預覽</title>   <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">   <meta http-equiv="description" content="This is my page">  </head>  <body>   <a href="<%=request.getContextPath()%>/BaiDuServlet?savFile=1234.xls">在線預覽</a>  </body></html>

六、 編寫baseFile.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><script type="text/javascript" src="../FlexPaper/js/flexpaper_flash.js"></script><style type="text/css">html,body{height: 100%;}body {  margin: 0;padding: 0;overflow: auto;}#flashContent { display:none; }</style></head><body><div style="position:absolute;left:10px;top:10px;">      <a id="viewerPlaceHolder" style="width:1000px;height:480px;display:block"></a>      <script type="text/javascript">         var fp = new FlexPaperViewer(	
             '../FlexPaper/FlexPaperViewer',             'viewerPlaceHolder', { config : {             SwfFile : escape('../reader/<%=(String)session.getAttribute("swfName")%>'),             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',             PrintPaperAsBitmap : false,             ViewModeToolsVisible : true,             ZoomToolsVisible : true,             NavToolsVisible : true,             CursorToolsVisible : true,             SearchToolsVisible : true,
  						 localeChain: 'zh_CN'             }});      </script>    </div></body></html>

注意baseFile.jsp中的代碼,不會你能夠參考這裏

/**************************************************************************************/

七、 到這裏就完成,須要注意的是:

一、  文件安裝路徑不要太深,否則 Java 調用外部命令不能執行,我這裏是 C盤下

二、 

2.一、紅色1標記路徑不能錯,我就犯這個錯誤了

2.二、紅色標記2還能夠寫 http://127.0.0.1:8080/baiduDoc/reader/...

三、 啓動OpenOffice的命令,不是直接雙擊啓動的。官網啓動方式,使用cd命令打開安裝目錄!

安裝完openoffice後

1.安裝服務

cd C:\Program Files (x86)\OpenOffice4\program

這一步你能夠看你的OpenOffice安裝哪裏

執行

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

2.查看是否安裝成功

2.1查看端口對應的pid

netstat -ano|findstr "8100"

2.2查看pid對應的服務程序名

tasklist|findstr "ipd值"

效果圖示:

源碼地址:

http://down.51cto.com/data/1980608

有問題留言,來找我吧!

相關文章
相關標籤/搜索