使用java编写,基于FlexPaper+swfTools仿文库文档在线阅读

一、文档在线阅读思路
    
    1.用OpenOffice把PPT、Word、Excel、Text转换为pdf
    2.用SWFTool将生成的pdf转换成swf,然后利用FlexPlayer实现在线预览播放

二、准备工作
    
    1.安装OpenOffice
      (1).官网下载地址:http://www.openoffice.org/download/index.html
           我使用的是4.1.3版本:Apache_OpenOffice_4.1.3_Win_x86_install_zh-CN.exe
      (2).启动OpenOffice服务
      CMD命令进入OpenOffice安装目录下的program目录:cd D:\tools\OpenOffice\program
      进入program目录后,输入:soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" –nofirststartwizard
      (3).查看OpenOffice服务
          a) cmd命令:netstat -ano|findstr "8100"
          显示如下内容则成功:          
          b) TCP    127.0.0.1:8100         0.0.0.0:0              LISTENING       6548
    2.下载JODConverter:http://sourceforge.net/projects/jodconverter/files/,项目中主要使用lib目录下的jar包。
    3.下载并安装SWFTools:http://www.swftools.org/download.html,下载exe文件安装完成即可
    4.下载FlexPlayer
http://pan.baidu.com/share/link?shareid=1181746637&uk=1913152192#dir/path=%2F%E8%BD%AF%E4%BB%B6%E5%B7%A5%E5%85%B7
       官网下载地址:http://flexpaper.devaldi.com/download/,版本为2.1.5,与1.5.1有较大差别,未使用最新版。

三、软件开发
      1.新建OfficeOnline项目,引入相应jar包(使用的是cos进行文档上传,cos.jar需要另外下载,也可使用commons-fileupload上传),
        将FlexPaper_1.5.1_flash.zip解压后的js目录引入到项目中,FlexPaperViewer.swf也引入进来    
        如下图:

2.新建DocConverter.java
        该文件用于将指定文件转换为pdf、再转换为swf文件 
        注意:根据SWFTools安装路径不同需要修改pdf2swf()方法中pdf2swf.exe的路径,我安装的路径是在D盘
         main()测试中根据自己文档路径进行修改测试。

package controllers.openoffice;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

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;

public class DocConverter {
	private static final Integer environment = 1;// 环境1:windows,2:linux(涉及pdf2swf路径问题)
	private String fileString;
	private String outputPath = "";// 输入路径,如果不设置就输出在默认位置
	private String fileName;
	private File pdfFile;
	private File swfFile;
	private File docFile;
	
	public DocConverter(String fileString) {
		ini(fileString);
	}

	/*
	 * 重新设置 file 
	 * @param fileString
	 */
	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) {
					// ToDo Auto-generated catch block
					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
	 */
	private void pdf2swf() throws Exception {
		Runtime r = Runtime.getRuntime();
		if (!swfFile.exists()) {
			if (pdfFile.exists()) {
				if (environment == 1) {// windows环境处理
					try {
						// 这里根据SWFTools安装路径需要进行相应更改
						Process p = r.exec("d:/tools/swftools/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 (Exception 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;
		//把InputStream字节流 替换为BufferedReader字符流 2013-07-17修改
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		StringBuilder buffer = new StringBuilder();
		while ((ptr = reader.read()) != -1) {
			buffer.append((char) ptr);
		}
		return buffer.toString();
	}

	/*
	 * 转换主方法
	 */
	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;
		}

		if (swfFile.exists()) {
			return true;
		} else {
			return false;
		}
	}

	/*
	 * 返回文件路径 @param s
	 */
	public String getswfPath() {
		if (swfFile.exists()) {
			String tempString = swfFile.getPath();
			tempString = tempString.replaceAll("\\\\", "/");
			return tempString;
		} else {
			return "";
		}
	}

	/*
	 * 设置输出路径
	 */
	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");
			}
		}
	}
	
	public static void main(String s[]) {
		DocConverter d = new DocConverter("E:/TDDOWNLOAD/test.docx");
		d.conver();
	}
}

3.新建OfficeOnLine.java 
   该文件用于处理控制器(controller)与视图(view)之间的交互

package controllers.openoffice;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

import play.Play;
import play.data.validation.Required;
import play.libs.Files;
import play.mvc.Controller;

public class OfficeOnLine extends Controller {
	
	/**
	 * 
	 * 文件上传页面
	 *
	 * @author 
	 * @date 2017年3月23日 下午2:02:12
	 */
	public static void documentUpload(){
		
	//	redirect("/MessageAction/messageDraftList");//重定向
		render();
	}
	
	/**
	 * 
	 * 预览页面
	 *
	 * 
	 * @author
	 * @date 2017年3月23日 下午3:29:07
	 */
	public static void documentView(String fileName, String filePath){
		
		render(fileName, filePath);
	}
	
	/**
	 * 
	 * 将上传的文件保存至指定位置
	 *
	 * @param file
	 * @throws IOException
	 * 
	 * @author
	 * @date 2017年3月24日 上午9:37:23
	 */
	public static void saveDocument(@Required File file) throws IOException{
		//文件上传采用cos组件上传,可更换为commons-fileupload上传,文件上传后,保存在upload文件夹
		//获取文件上传路径
		String saveDirectory = "public/upload/";
		File dir = new File(saveDirectory);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        
        String fileName = file.getName();
        
        Files.copy(file, Play.getFile("public/upload/" + fileName)); //存到upload文件夹里面 filename将作为文件的名字
        
        String uploadFilePath = saveDirectory + fileName;
        	
		documentView(fileName, uploadFilePath);
	}
	
	public static void getSwfFile(@Required String fileName){
		String filePath = "public/upload/" + fileName;
		
		//判断文件是否存在
		File file = new File(filePath);
		if (!file.isFile()) {
			renderJSON("1000");
		}
		
		//调用转换类DocConverter,并将需要转换的文件传递给该类的构造方法
		DocConverter d = new DocConverter(filePath);
		//调用conver方法开始转换,先执行doc2pdf()将office文件转换为pdf;再执行pdf2swf()将pdf转换为swf;
		d.conver();
		//调用getswfPath()方法,打印转换后的swf文件路径
		
		Map<String, String> result = new HashMap<String, String>();
		result.put("swfFilePath", "/"+d.getswfPath());
		
		renderJSON(result);
	}
}

4.新建documentUpload.html
   该页面用于文件上传

<!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>
	
	<style type="text/css">
		body {
			margin-top: 100px;
			background: #fff;
			font-family: Verdana, Tahoma;
		}
		
		a {
			color: #CE4614;
		}
		
		#msg-box {
			color: #CE4614;
			font-size: 0.9em;
			text-align: center;
		}
		
		#msg-box .logo {
			border-bottom: 5px solid #ECE5D9;
			margin-bottom: 20px;
			padding-bottom: 10px;
		}
		
		#msg-box .title {
			font-size: 1.4em;
			font-weight: bold;
			margin: 0 0 30px 0;
		}
		
		#msg-box .nav {
			margin-top: 20px;
		}
     </style>
</head>

<body>
	<div id="msg-box">
			<form name="form1" method="post" enctype="multipart/form-data" action="@{openoffice.OfficeOnLine.saveDocument()}">
				<div class="title">
					请上传要处理的文件,过程可能需要几分钟,请稍候片刻。
				</div>
				<p>
					<input name="file" type="file">
				</p>
				<p>
					<input type="submit" name="Submit" value="上传">
				</p>
			</form>
    </div>
</body>
</html>

5.新建documentView.html 
   该页面用于文档在线预览

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>

		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<title>文件预览</title>
		
		<style type="text/css" media="screen">
	          html, body {
	              height: 100%;
	         }
	 
	         body {
	             margin: 0;
	             padding: 0;
	             overflow: auto;
	         }
	         
	         #flashContent {
			    position:absolute;
 				left:0px;
 				top:80px;
 				width:900px;
 				height:500px;
 				z-index:1;
 				border:solid #7A7A7A 4px; 
			}
        </style>
		
        <script type="text/javascript" src="@{'/public/js/jquery-1.11.1.min.js'}"></script>
		<script type="text/javascript" src="@{'/public/js/swfobject.js'}"></script>
		<script type="text/javascript" src="@{'/public/js/flexpaper_flash.js'}"></script>
		<script type="text/javascript" src="@{'/public/js/flexpaper_flash_debug.js'}"></script>
		
	    <script type="text/javascript">
		    $(function(){
		    	$("#flashContent").hide(); //先让div隐藏
	            $("#span1").click(function(){
	            	getSwfFile("${fileName}");
	                $("#flashContent").fadeIn("slow");//淡入淡出效果 显示div
	            });
				
	            $("#span2").click(function(){
	                 $("#flashContent").fadeOut("slow");//淡入淡出效果 隐藏div
	            })
		    });
		    
		    //获取上传文件的swf文件
	    	var getSwfFile = function(fileName){
	    		$.ajax({
	    			url : '/openoffice.OfficeOnLine/getSwfFile',
	    			type : 'POST',
	    			async : false,
	    			data : {"fileName":fileName},
	    			datatype : 'json',
	    			success : function(data) {
		    			if (data != "1000") {
		    				documentShow(data.swfFilePath);
		    			}
	    			},
	    			error : function() {
	    				alert('获取swf文件异常');
	    			}
	    		});
	    	}
	    	
    	    function documentShow(filePath){
        	  <!-- For version detection, set to min. required Flash Player version, or 0 (or 0.0.0), for no version detection. -->
              var swfVersionStr = "10.0.0";
              <!-- To use express install, set to playerProductInstall.swf, otherwise the empty string. -->
              var xiSwfUrlStr = "playerProductInstall.swf";
			  
              var flashvars = {
                  SwfFile: encodeURI(filePath),//要显示的swf文件,并设置编码
                  Scale: 0.9,//缩放比例
                  ZoomTransition: "easeOut",//Flexpaper中缩放样式,它使用和Tweener一样的样式,默认参数值为easeOut.其他可选值包括: easenone, easeout, linear, easeoutquad
                  ZoomTime: 0.5,//从一个缩放比例变为另外一个缩放比例需要花费的时间,该参数值应该为0或更大。
                  ZoomInterval: 0.1,//缩放比例之间间隔,默认值为0.1,该值为正数。
                  FitPageOnLoad: false,//初始化的时候自适应页面,与使用工具栏上的适应页面按钮同样的效果。
                  FitWidthOnLoad: true,//初始化的时候自适应页面宽度,与工具栏上的适应宽度按钮同样的效果。
                  PrintEnabled: true,//是否支持打印
                  FullScreenAsMaxWindow: false,//是否支持全屏,当设置为true的时候,单击全屏按钮会打开一个
                  ProgressiveLoading: true,//当设置为true的时候,展示文档时不会加载完整个文档,而是逐步加载,但是需要将文档转化为9以上的flash版本(使用pdf2swf的时候使用-T 9 标签)
                  PrintToolsVisible: true,
                  SearchMatchAll: true,//设置为true的时候,单击搜索所有符合条件的地方高亮显示。
                  ViewModeToolsVisible: true,//工具栏上是否显示样式选择框(就是显示缩略图或分页显示的工具)
                  ZoomToolsVisible: true,//工具栏上是否显示缩放工具
                  FullScreenVisible: true,
                  NavToolsVisible: true,//工具栏上是否显示导航工具(也就是页码工具)
                  CursorToolsVisible: true,//工具栏上是否显示光标工具
                  SearchToolsVisible: true,//工具栏上是否显示搜索
                  localeChain: "zh_CN"//语言  en_US (English) 、zh_CN (Chinese, Simple)
           	 };
              
             var params = {
              }
              params.quality = "high";
              params.bgcolor = "#ffffff";
              params.allowscriptaccess = "sameDomain";
              params.allowfullscreen = "true";
              var attributes = {};
              attributes.id = "FlexPaperViewer";
              attributes.name = "FlexPaperViewer";
              swfobject.embedSWF(
             	"@{'/public/swf/FlexPaperViewer.swf'}", "flashContent2",//flashContent2为div的唯一标识
                  "900", "500",
                  swfVersionStr, xiSwfUrlStr,
                  flashvars, params, attributes);
              swfobject.createCSS("#flashContent2", "display:block;text-align:left;");//样式
        }
	 </script>
</head>

<body>
       <div  style="position:absolute;left:30%;top:10%;">
         <div>
         	<span>${fileName}</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" style="cursor:pointer" id="span1">预览</a>
         </div>
         <div id="flashContent">
         	<div align="right" style="background-color:#CDCDCD;"><span id="span2" style="cursor:pointer">关闭</span></div>
         	<!-- <div>
	             <p>
	                 To view this page ensure that Adobe Flash Player version 10.0.0 or greater is installed.
	             </p>
	             <script type="text/javascript">
	                 var pageHost = ((document.location.protocol == "https:") ? "https://" : "http://");
	                 document.write("<a href='http://www.adobe.com/go/getflashplayer'><img src='"
	                                 + pageHost + "www.adobe.com/images/shared/download_buttons/get_flash_player.gif' alt='Get Adobe Flash player' /></a>");
	             </script>
             </div> -->
             <div id="flashContent2">
             	
             </div>
        </div>
       </div> 
</body>
</html>

FlexPaperViewer参数设置对应说明文档:http://flexpaper.devaldi.com/docs_parameters.jsp

6.运行结果如下

 (1).上传页面

134327_BqeY_3225458.png

点击上传,页面跳转至预览页面

134429_MR3R_3225458.png

点击预览,查看文件内容

134513_dwnO_3225458.png

四、其他优化

1.若出现swf无法预览,
http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04a.html#119065
      将生成swf的文件夹设置为信任文件。
    2.参考资料:http://blog.csdn.net/hil2000/article/details/8459940
                        http://www.cnblogs.com/star-studio/archive/2011/12/09/2281807.html
                        文件中文名乱码解决:http://blog.csdn.net/kunoy/article/details/7903258
    3.如果flexpaper不满足你的要求,也可以对其进行二次开发,这里推荐两篇文章,希望对您有所帮助:
       http://www.cnblogs.com/xcong/archive/2013/06/20/3142155.html
       http://www.cnblogs.com/zamlove/archive/2013/05/07/3065079.html 
    4.解决flexpaper搜索文字时不能高亮的问题: http://my.oschina.net/dianfusoft/blog/125450 
       flexpaper去简介去水印等:http://blog.csdn.net/zengraoli/article/details/7827840

转载于:https://my.oschina.net/dami1203/blog/868288

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值