加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用SSH实现在线文档阅读(类似百度文库)

发布时间:2020-12-15 04:33:32 所属栏目:百科 来源:网络整理
导读:最近在项目中需要用到像百度文库一样的可以用来在线阅读的形式,由于大部分的文件都是doc,xls和ppt,经过多方查找,明白了大概的实现原理就是:先将office文件转化为pdf,然后将所得到的pdf文件转化为swf格式的文件,最后在页面上通过FlexPaper来查看所得到的

最近在项目中需要用到像百度文库一样的可以用来在线阅读的形式,由于大部分的文件都是doc,xls和ppt,经过多方查找,明白了大概的实现原理就是:先将office文件转化为pdf,然后将所得到的pdf文件转化为swf格式的文件,最后在页面上通过FlexPaper来查看所得到的swf文件。基本过程的如下:

一、所用的工具:

工具

OpenOffice

http://zh.openoffice.org/new/zh_cn/downloads.html

JodConverter

http://sourceforge.net/projects/jodconverter/files/

Swftools

http://www.swftools.org/

FlexPaper

http://flexpaper.devaldi.com/


下载完后,需要安装OpenOffice和Swftools两个文件,文件安装路径最好不要有中文和空格!然后将

JodConverter压缩包中lib目录下的jar包,全部复制进项目中的lib包下即可。

安装完OpenOffice后必须开启OpenOffice服务,有以下几种方法开启:

第一种: 以命令的方式开启openoffice的服务

? ? 在cmd命令下,cd opeonofiice的安装路径/program 如:

cd c:program filesopenoffice.org 3program soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" 

第二种 :系统开启openoffice的服务

? ? 在系统开启openoffice的服务我们还需要一个Windows Resource Kit tools ,将openoffice server设为系统服务。Windows Resource Kit tools 是微软专为管理人员、开发人员和高级用户开发的,包括管理活动目录、组策略、TCP/IP网络、注册表、系统安全、监测等涉及Windows Server 2003 操作系统的其它很多方面的非常规安装的工具组件。Resource Kit Tools for XP的发布使得XP用户也能使用Resource Kit Tools对这些问题进行处理。

? ? 下载windows resource kit tools,我们进行默认安装。

???? 1.打开Windows Resource Kit Tools

???? 在Command Shell执行以下命令:

 "C:Program FilesWindows Resource KitsToolsinstsrv" OpenOfficeUnoServer "C:Program FilesWindows Resource KitsToolssrvany.exe"

打开 管理工具->服务 可以找到以 OpenOfficeUnoServer 命名的服务

??? 2.打开注册表寻找以下路径

??? HKEY_LOCAL_MACHINE -> SYSTEM ->ControlSet001 ->Services ->OpenOfficeUnoServer

? 新建项 Parameters,在该项下添加两个字符串值:

  key:Application

???? value:C:Program FilesOpenOffice.org 3programsoffice.exe

???? key:AppParameters

?????value:-invisible -headless -accept=socket,port=8100;urp; -nofirststartwizard

???? 3.在服务控制台,启动 openoffice 服务

???? 4.在CMD中用以下命令查看8100是否已被监听:netstat -anop tcp

这样OpenOffice3.0就以服务方式运行在Windows系统上了。(使用cmd命令:netstat -anp tcp查看8100端口是否工作)

然後可以通过socket方式连接openOffice,以使用openoffice提供的某些服务,如文件转换服务,ms office转pdf等等。

开源项目 JODConverter 就是结合openoffice来进行文档转换的java组件。

另外有一个命令行工具swftools,该工具可以将pdf转换为swf格式的文档,提供给ie客戶端流览。????

  另外,我们可以将该配置用bat文件来快速实现,运行前请先修改相应目录参数:

???? openoffice service.bat文件

??? "C:Program FilesWindows Resource KitsToolsinstsrv" OpenOfficeUnoServer "C:Program FilesWindows Resource KitsToolssrvany.exe"
??? reg add HKEY_LOCAL_MACHINESYSTEMControlSet001servicesOpenOfficeUnoServerParameters /ve /d
??? reg add HKEY_LOCAL_MACHINESYSTEMControlSet001servicesOpenOfficeUnoServerParameters /v Application /t REG_SZ /d "C:Program FilesOpenOffice.org 3programsoffice.exe"
??? reg add HKEY_LOCAL_MACHINESYSTEMControlSet001servicesOpenOfficeUnoServerParameters /v AppParameters /t REG_SZ /d "-invisible -headless -accept=socket,port=8100;urp; -nofirststartwizard"

这两种方法都比较麻烦,而且每次如果是手动开启命令的话很不方便。所以有了第三种方案:通过java代码开启服务,这个方法主要是在进行转换文档时自动开启OpenOpenoffice的服务,转换完成后自动关闭。

第三种方案: java代码开启服务

? ?java代码开启服务主要的是在转换文档的过程中每次转换之前先进行startserveice ,执行转换,stopservice。主要的代码将在后面的实例中列出!


二、代码演示:

(1)由于项目中需要转换的地方不只一处,所以将需要转换的代码写成了一个帮助类如下:

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;  


/** 
 * office文档格式转换 
 *  
 * @author Administrator 
 *  
 */  
public class DocConverter {
	private static final int environment = 1;// 环境 1:windows 2:linux  
	private String fileString;//源文件的路径	
	private String outputPath = "D:/javaserve/tomcat/apache-tomcat-7.0.32/webapps/jingpinkecheng/flexpaper/file";// 输出路径 ,如果不设置就输出在默认的位置 (与源文件位置相同)
	private String openoffice_home = "D:/Program Files/OpenOffice.org 3";//这里是OpenOffice的安装目录
	private String pdf2swf_home = "E:/javaserver/swftools/pdf2swf.exe ";//pdf2swf的安装路径
	private String fileName;
	private File officeFile;//office文件
	private File pdfFile;//转成的pdf文件
	private File swfFile;//转成的swf文件
	 
	
	public DocConverter(String fileString) {  
		//this.swfFile = swfFile;
		ini(fileString);  
	}  
	
	/**
	 * 在调用转换类的时候将输出路径、OpenOffice的安装路径、pdf2swf的路径都设置好,若路径都一样,可直接在属性上设置更方便
	 * @param fileString
	 * @param outputPath
	 * @param OpenOffice_Home
	 * @param pdf2swf_home
	 */
	public DocConverter(String fileString,String outputPath,String openoffice_home,String pdf2swf_home){
		this.outputPath = outputPath;
		this.openoffice_home = openoffice_home;
		this.pdf2swf_home = pdf2swf_home;
		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("."));  
		officeFile = new File(fileString); 
		pdfFile = new File(fileName + ".pdf");  
		setOutputPath(outputPath);
		
	}  
	
	/** 
	* 转为PDF 
	*  
	* @param file 
	*/  
	private void doc2pdf() throws Exception {  
		if (officeFile.exists()) {  
			if (!pdfFile.exists()) {  
				
				// 如果从文件中读取的URL地址最后一个字符不是 '',则添加''  
	            if (openoffice_home.charAt(openoffice_home.length() - 1) != '') {  
	            	openoffice_home += "";  
	            }  
	            
	            // 使用java启动OpenOffice的服务 
	            String command = openoffice_home  
	                    + "programsoffice.exe -headless -accept="socket,port=8100;urp;"";  
	            Process pro = Runtime.getRuntime().exec(command);
				OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);  
				try {  
					connection.connect();  
					DocumentConverter converter = new OpenOfficeDocumentConverter(  
					connection);  
					converter.convert(officeFile,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 
	*/  
	private void pdf2swf() throws Exception {  
		Runtime r = Runtime.getRuntime();  
		if (!swfFile.exists()) {  
			if (pdfFile.exists()) {  
				if (environment == 1) {// windows环境处理  
					try { 
						//以下的参数:-G -s poly2bitmap非常重要,特别是碰到office文件中文件特别大或者说图表特别多的情况,可能无法转为swf文件,加上这可以防止,
						//具体参数请参考网上资料。由于这样会降低转换效率,所以最好在这里做个判断,若文件大于某个大小再加这两个参数,反之不用加,提高转换效率
						Process p = r.exec(pdf2swf_home + pdfFile.getPath() + " -o "+ swfFile.getPath() + " -T 9 -G -s poly2bitmap");  
						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();  
	}  
	
	/** 
	* 转换主方法 
	*/  
	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("/")+1,fileString.lastIndexOf("."));  
			//判断输出路径最后是否有"/",如果没有的话,输出时要加上一个"/"
			if (outputPath.charAt(outputPath.length()-1) == '/') {  
				swfFile = new File(outputPath + realName + ".swf");  
			} else {  
				swfFile = new File(outputPath + "/" + realName + ".swf");  
			}  
		} else {
			swfFile = new File(fileName + ".swf"); 
		}
	}  
		
		/*public static void main(String s[]) {  
			DocConverter d = new DocConverter("C:/upload/Power_Point的使用技巧.ppt");  
			d.conver();  
		}  			*/									
}

(2)action中的属性设置:

	private Item netkejianyanshi;//所查找的对象

(3)转换源文件为pdf及转换pdf为swf格式

public String showNetKejianyanshi() throws IOException{
		
		netkejianyanshi = itemService.findById(netkejianyanshiid);


		System.out.println(netkejianyanshi.getContent());
		DocConverter converter = new DocConverter("F:/java/work/jingpinkecheng/WebRoot/flexpaper/file/"+netkejianyanshi.getFirst_img());
		converter.conver();
		
		HttpSession session = request.getSession();
		String fileName = netkejianyanshi.getFirst_img();
		fileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");//存到session后在jsp页面取出的值是乱码,所以这里先变成ISO-8859-1("乱码"),传输过去之后即可消除
		session.setAttribute("fileName",fileName.substring(0,fileName.lastIndexOf("."))+".swf");
		System.out.println("我是测试:"+session.getAttribute("fileName"));
		 return "success";
	}

(4)经过以上的过程,已经将源文件转化为了swf文件,接下来就得通过FlexPaper将swf文件显示出来,在这之前,有几件事得先做一下:

①将FlexPaper包解压缩,打开根目录下的index.html,看看官方提供的Paper.swf文件能否正常的显示(能正常显示的话跳过这一步),如果不能,则是由于Flexpaper还没获得Adobe Flash的信任,这时你可以前往http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04a.html#119065?为FlexPaper添加信任.进入网页之后 ,点击左边的 Global Security Settings papel 这个选项,然后在右边(如下图)

为你的例子所在的文件夹添加信任。然后你再运行官方的例子,即可将官方的文档运行成功!这一步不能省,因为后面不能显示的原因有很多,如果是因为这个原因导致的话,那就太费事费力了!

②如果官方的例子能运行的话,那第二步就是查看官方的index.html的源代码如下:

<!doctype html>
<html>
<head>
    <title>FlexPaper</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <style type="text/css" media="screen">
        html,body	{ height:100%; }
        body { margin:0; padding:0; overflow:auto; }
        #flashContent { display:none; }
    </style>
    <!--将项目中的这几个css及js文件导入,路径一定要正确-->
    <link rel="stylesheet" type="text/css" href="css/flexpaper.css" />
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript" src="js/flexpaper.js"></script>
    <script type="text/javascript" src="js/flexpaper_handlers.js"></script>
</head>
<body>
<!--这是用于显示文档的flexpaper显示器的位置,具体的大小可以自己设置-->
<div style="position:absolute;left:10px;top:10px;">
<div id="documentViewer" class="flexpaper_viewer" style="width:770px;height:500px"></div>

<script type="text/javascript">
    function getDocumentUrl(document){
        return "php/services/view.php?doc={doc}&format={format}&page={page}".replace("{doc}",document);
    }

    var startDocument = "Paper";

    $('#documentViewer').FlexPaperViewer(
            { config : {

                SWFFile : 'docs/Paper.swf',//这里就是所要显示的swf文件的具体位置,关键点还是路径的配置

                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',RenderingOrder : 'flash,html',StartAtPage : '',ViewModeToolsVisible : true,ZoomToolsVisible : true,NavToolsVisible : true,CursorToolsVisible : true,SearchToolsVisible : true,WMode : 'window',localeChain: 'en_US'
            }}
    );
</script>

将以上的代码复制到自己所要显示的页面,将路径改为自己的文件所在的具体路径,这样在前台就可以显示最终的swf文件了!

③如果官方的文档可以显示,但是自己的文件却无论如何也出不来,有以下三种情况:

<1>首要看的就是有没有转化成swf文件,一般转成pdf文件都没有问题,但是如果pdf文件是通过.xls和.ppt文件转化过来的时候,里面会有很多的表格,而且一般情况下文件都比较大,这样的话,在将pdf转成swf文件时就会出错(可能转成了但文件是空的,又或者根本就转不成swf),所以一定要先检查是否已经成功转成了并将转成的swf文件放在官方的flexpaper下看看是否能显示!

<2>如果有文件但是却显示不了,检查路径是否写正确了,可以以相对于网站的根目录的绝对路径来尝试看是否是可以显示

<3>版本的问题。如果文件存在,而且路径都写正确了,则是转成的swf文件版本的问题。通过swftools工具转化成的swf文件一般都是7或8版本的,而至少只有9的版本才能在flexpaper上显示,此时可以再命令行中进行转换,不过我在项目中不可能每次都在命令行输入,所以只有在java代码中直接转换为9版本的,上面的代码中已经转换过了:

Process p = r.exec(pdf2swf_home + pdfFile.getPath() + " -o "+ swfFile.getPath() + " -T 9 -G -s poly2bitmap");//这里的-T 9即代表版本转换
至此,即可完成在线文档的浏览了!效果如下所示:


参考资料:

http://www.voidcn.com/article/p-uzdpehrl-bdt.html

http://wenku.baidu.com/view/6336ec8d83d049649b66582a.html

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读