Java實現office文檔與pdf文檔的在線預覽功能


      最近項目有個需求要java實現office文檔與pdf文檔的在線預覽功能,剛剛接到的時候就覺得有點難,以自己的水平難以在三四天做完。壓力略大。后面查找百度資料、以及在同事與網友的幫助下,四天多把它做完。查找資料發現我們要實現的過程就是把office轉換成pdf,當然pdf就不用轉換了。然后在pdf轉換為swf文件,在瀏覽器實現預覽swf文件。整個過程就是這樣,看起來很簡單,實際操作起來會出現各種問題。下面我就把自己寫的這一小功能記錄下來。

1、首先我們需要找到可以把office轉換成pdf的方法,查找資料發現有openoffice這一軟件可以把office轉換成pdf,這一軟件先下載下來,然后記住自己安裝的在那個位置。然后在cmd環境下進入安裝目錄的program目錄,輸入打開openoffice的命令:

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

輸入完成之后在任務管理器可以看見soffice.bin的進程在任務管理器,這一服務就啟動成功。當然在代碼中轉換office2pdf我們還需要一些架包。下載jodconverter-2.2.2架包,然后復制到lib目錄下,引入架包就可以了。這個架包有如下包:

 

有一些項目重復的可以刪除,根據實際情況自己處理。

 

2、我們需要找到轉換pdf2swf的方法。查找資料發現swftools這個軟件可以把pdf轉換成swf文件。把它下下來安裝好就可以了。

 

3、我們需要一個展示swf文件的容器,發現有flexpaper這個插件。而且展示效果還不錯。所以我們需要下載這個插件。使用這個插件需要有三個js文件。分別是:jquery.jsflexpaper_flash.jsflexpaper_flash_debug.js。插件的名字是FlexPaperViewer.swf

 

整個項目結如下:

准備工作完成下面開始編碼.

轉換類為DocConverter 的代碼:

 

package com.cectsims.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
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;


/**
 * doc docx格式轉換 
 */
public class DocConverter {
	private static final int environment = 1;// 環境 1:Windows 2:Linux
	private String fileString;// (只涉及PDF2swf路徑問題)
	private String outputPath = "";// 輸入路徑 ,如果不設置就輸出在默認 的位置
	private String fileName;
	private File pdfFile;
	private File swfFile;
	private File docFile;

	public DocConverter(String fileString) {
		ini(fileString);
		System.out.println("文件路徑"+fileString);
	}

	/**
	 * * 重新設置file
	 * 
	 * @param fileString
	 *            32.
	 */
	public void setFile(String fileString) {
		ini(fileString);
	}

	/**
	 *  * 初始化 
	 * 
	 * @param fileString
	 *           
	 */
	private void ini(String fileString) {
		this.fileString = fileString;
		fileName = fileString.substring(0, fileString.lastIndexOf("."));
		docFile = new File(fileString);
		pdfFile = new File(fileName+ ".pdf");
		swfFile = new File(fileName+ ".swf");
	}

	/**
	 *  轉為PDF 
	 * 
	 * @param file
	 *       
	 */
	private void doc2pdf() throws Exception {
		if (docFile.exists()) {
			if (!pdfFile.exists()) {
				OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
				try {
					connection.connect();
					DocumentConverter converter = new OpenOfficeDocumentConverter(
							connection);
					converter.convert(docFile, pdfFile);
					// close the connection
					connection.disconnect();
					System.out.println("****pdf轉換成功,PDF輸出: "+ pdfFile.getPath() + "****");
				} catch (java.net.ConnectException e) {
					e.printStackTrace();
					System.out.println("****swf轉換器異常,openoffice 服務未啟動!****");
					throw e;
				} catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {
					e.printStackTrace();
					System.out.println("****swf轉換器異常,讀取轉換文件 失敗****");
					throw e;
				} catch (Exception e) {
					e.printStackTrace();
					throw e;
				}
			} else {
				System.out.println("****已經轉換為pdf,不需要再進行轉化 ****");
			}
		} else {
			System.out.println("****swf轉換器異常,需要轉換的文檔不存在, 無法轉換****");
		}
	}

	/** * 轉換成 swf */
	@SuppressWarnings("unused")
	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:/Program/swfttools/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已經存在不需要轉換****");
		}
	}

	static 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();
	}

	/**
	 * * 轉換主方法
	 */
	@SuppressWarnings("unused")
	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;
		}
		System.out.println("文件存在嗎?"+swfFile);
		if (swfFile.exists()) {
			System.out.println("存在");
			return true;
		} else {
			System.out.println("不存在");
			return false;
		}
	}

	/**
	 *返回文件路徑      
	 * @param     
	 */
	public String getswfPath(){
		if (this.swfFile.exists()){
			String tempString = swfFile.getPath();
			tempString = tempString.replaceAll("\\\\", "/");
			System.out.println("最后文件路徑為"+tempString);
			return tempString;
		} else {
			return "文件不存在";
		}
	}

	/**
	 * 設置輸出路徑
	 * 
	 * @param outputPath
	 */
	public void setOutputPath(String outputPath){
		this.outputPath = outputPath;
		if (!outputPath.equals("")) {
			String realName = fileName.substring(fileName.lastIndexOf("/"),
					fileName.lastIndexOf("."));
			if (outputPath.charAt(outputPath.length()) == '/') {
				swfFile = new File(outputPath + realName + ".swf");
			} else {
				swfFile = new File(outputPath + realName + ".swf");
			}
		}
	}
}

 

  

調用轉換類只需要傳wordpttexcelpdf文件所在的路徑參數就可以了。

展示在線預覽的jsp代碼如下:

 

<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
   String swfFilePath=session.getAttribute("swfpath").toString();
   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.js"></script>
<script type="text/javascript" src="js/flexpaper_flash.js"></script>
<script type="text/javascript" src="js/flexpaper_flash_debug.js"></script>
<!--  <script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="js/flexpaper.js"></script>
<script type="text/javascript" src="js/flexpaper_handlers.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:escape('<%=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:'en_US'}});
          </script>
   </div>
</body>
</html>

 

其中可能會出現在線預覽只能實現10頁的情況,需要把RenderingOrder : 'flash',設置為flash才可以實現超過10頁的在線預覽。swfFilePat為轉換后的文件所在路徑。

轉換后面的效果如下:

注意問題:

1、發現錯誤一般是openoffice服務沒有開啟。

2、Linux環境下會存在中文亂碼的問題,是linux下不像windows支持那么多字體,需要安裝多的字體,並且把字體所在位置鏈接到flexpaper所在位置。在使用pdf2swf加上參數-s languagedir=/usr/local/xpdf-chinese-simplified/。具體的一些參數請百度。

源代碼已經在我的github上了,可以訪問https://github.com/liaowp/OnlinePreview,也可以點擊我博客的github標簽。

如果有問題可以加QQ群咨詢。178737461

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM