Spring 最实用的文档在线预览(利用OpenOffice+swftools+FlexPaper实现)

废话不多说,直接上代码,实践过程有问题,私信即可:

环境准备:

一、OpenOffice:将不同类型的office文件转换为pdf文件

二、swftools:将pdf文件转换为swf文件

三、FlexPaper:使用FlexPaper 在jsp中预览swf文件

四、下载地址:

说明:亲自项目实践可用,FlexPaper用百度网盘中的文件,OpenOffice和swftools点击下面下载即可

https://download.****.net/download/ysh598923879/11065490

使用到的JS文件:flexpaper_flash.js和flexpaper_flash_debug.js及FlexPaperViewer.swf文件

链接:https://pan.baidu.com/s/1mrQeohjQD5hyPNh9Bb9C-w      提取码:mo2f 

 

五、提示:解压FlexPaper后,将FlexPaperViewer.swf文件拷贝至webapps目录下:

Spring 最实用的文档在线预览(利用OpenOffice+swftools+FlexPaper实现)

 

六、软件使用说明

安装完OpenOffice后,还需要启动OpenOffice Server。

1.以命令行方式启动OpenOffice Server

在安装目录:C:\Program Files (x86)\OpenOffice 4\program下,按住shift键,鼠标右键,在此处打开命令窗口,执行以下命令即可:soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard

 

七、前后台代码

1、前台代码:

1、HTML中引入flexpaper_flash.js和flexpaper_flash_debug.js文件,具体代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%
	String swfFilePath = session.getAttribute("swfFilepath").toString();
%>
<!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">
<script type="text/javascript"
	src="${pageContext.request.contextPath}/resource/js/jquery.js"></script>
<script type="text/javascript"
	src="${pageContext.request.contextPath}/resource/js/flexpaper_flash.js"></script>
<script type="text/javascript"
	src="${pageContext.request.contextPath}/resource/js/flexpaper_flash_debug.js"></script>
<style type="text/css" media="screen">
html, body {
	height: 100%;
}

body {
	margin: 0;
	padding: 0;
	overflow: auto;
	width: 100%;
	height: 100%;
}

#flashContent {
	display: none;
}
</style>
<title>文档在线预览系统</title>
</head>
<body>
<div style="position: absolute; top: 10px; width: 100%; height: 100%;">
	<a id="viewerPlaceHolder"
		style="width: 820px; height: 650px; display: block; width: 100%; height: 80%;">    
    </a>
	<script type="text/javascript"> 
		var fp = new FlexPaperViewer(	
			'FlexPaperViewer',
			'viewerPlaceHolder', {  //文件预览的<a>标签的id(即上方<a>标签的id)
			 config : {
				 SwfFile : "<%=swfFilePath%>",//后台返回的文件路径
				 Scale : 0.6,
				 ZoomTransition : 'easeOut',//变焦过渡
				 ZoomTime : 0.5,
				 ZoomInterval : 0.2,//缩放滑块-移动的缩放基础[工具栏]
				 FitPageOnLoad : true,//自适应页面
				 FitWidthOnLoad : true,//自适应宽度
				 FullScreenAsMaxWindow : false,//全屏按钮-新页面全屏[工具栏]
				 ProgressiveLoading : false,//分割加载
				 MinZoomSize : 0.2,//最小缩放
				 MaxZoomSize : 3,//最大缩放
				 SearchMatchAll : true,
				 InitViewMode : 'Portrait',//初始显示模式(SinglePage,TwoPage,Portrait)
				 ViewModeToolsVisible : true,//显示模式工具栏是否显示
				 ZoomToolsVisible : true,//缩放工具栏是否显示
				 NavToolsVisible : true,//跳页工具栏
				 CursorToolsVisible : false,
				 SearchToolsVisible : true,
				 PrintPaperAsBitmap:false,
				 localeChain: 'zh_CN'
			 }
		});
	</script>
</div>
</body>
</html>

2、后台代码:

// 文件转换工具类
public class DocConverter {
	
	// 重点:此路径为swf软件的安装路径,根据自身情况修改
	private String SWFTools_Windows = "C:/SWFTools/pdf2swf.exe ";
	private String fileString;
	// private String outputPath;// 输入路径,如果不设置就输出在默认位置
	private String fileName;
	private File pdfFile;
	private File swfFile;
	private File docFile;
	private File odtFile;

	public DocConverter(String fileString) {
            ini(fileString);
	}

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

	/*
	 * 初始化 @param fileString
	 */
	private void ini(String fileString) {                                                                                                                 
        try {
	    this.fileString = fileString;
	    fileName = fileString.substring(0, fileString.lastIndexOf("/"));
	    docFile = new File(fileString);
            String s = fileString.substring(fileString.lastIndexOf("/") + 1, fileString.lastIndexOf("."));
		fileName = fileName + "/" + s;
		// 用于处理TXT文档转化为PDF格式乱码,获取上传文件的名称(不需要后面的格式)
		String txtName = fileString.substring(fileString.lastIndexOf("."));
		// 判断上传的文件是否是TXT文件
		if (txtName.equalsIgnoreCase(".txt")) {
			// 定义相应的ODT格式文件名称
			odtFile = new File(fileName + ".odt");
			// 将上传的文档重新copy一份,并且修改为ODT格式,然后有ODT格式转化为PDF格式
			this.copyFile(docFile, odtFile);
			pdfFile = new File(fileName + ".pdf"); // 用于处理PDF文档
		} else if (txtName.equals(".pdf") || txtName.equals(".PDF")) {
			pdfFile = new File(fileName + ".pdf");
		} else {
			pdfFile = new File(fileName + ".pdf");
		}
		swfFile = new File(fileName + ".swf");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @Title: copyFile 
	 */
	private void copyFile(File sourceFile, File targetFile) throws Exception {
		// 新建文件输入流并对它进行缓冲 
		FileInputStream input = new FileInputStream(sourceFile);
		BufferedInputStream inBuff = new BufferedInputStream(input);
		// 新建文件输出流并对它进行缓冲
		FileOutputStream output = new FileOutputStream(targetFile);
		BufferedOutputStream outBuff = new BufferedOutputStream(output);
		// 缓冲数组 
		byte[] b = new byte[1024 * 5];
		int len;
		while ((len = inBuff.read(b)) != -1) {
			outBuff.write(b, 0, len);
		}
		// 刷新此缓冲的输出流
		outBuff.flush();
		// 关闭流
		inBuff.close();
		outBuff.close();
		output.close();
		input.close();
	}

	/*
	 * 转为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
	 */
	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(SWFTools_Windows + " -t " + pdfFile.getPath() + " -s flashversion=9 -o "
							+ swfFile.getPath());
					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 {
				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****");
		// }

		try {
			String txtName = fileString.substring(fileString.lastIndexOf("."));
			if (txtName != null && !txtName.equals(".pdf")) {
				doc2pdf();
			}
			pdf2swf();
		} catch (Exception e) {
			// TODO: Auto-generated catch block
			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 "";
		}
	}

}
/**
 * 预览文件
 * @throws Exception 
 */
@RequestMapping("/viewFileOnline.do")
@ResponseBody
public ModelAndView viewFileOnline(HttpServletRequest rq,HttpServletResponse rs) throws Exception {
	
	// 获取预览文件的路径
	setEncodingUTF8(rq, rs);
	String tomcatServerPath = System.getProperty("catalina.home");
	tomcatServerPath = tomcatServerPath.replace("\\", "/");
	String oldFilePath = "d:/test.docx";
	String newFilePath = tomcatServerPath + "/test.docx";
	// 移动到服务器应用目录下
        FileUtil.copyFile(oldFilePath, newFilePath);
	DocConverter converter = new DocConverter(newFilePath);
	converter.conver(); // 将test.docx转换为swf文件
	String getswfPath = converter.getswfPath(); // 获取生成的swf文件的绝对路径
        // 因为swf文件需要在tomcat的相对路径下才能访问到,所以截取tomcat的相对路径,upload为自建目录
	String swfFilepath = "upload" +  getswfPath.substring(getswfPath.lastIndexOf("/"));
	rq.getSession().setAttribute("swfFilepath", swfFilepath); // 将swf文件路径返回给前台
	ModelAndView mav = new ModelAndView("/previewFile");
	
	return mav;
} 

3、pom.xml文件添加如下依赖:

1、pom.xml添加如下依赖:

<dependency>
    <groupId>net.sf.json-lib</groupId>
    <artifactId>json-lib</artifactId>
    <version>0.9</version>
</dependency>
<dependency>
    <groupId>com.artofsolving</groupId>
    <artifactId>jodconverter</artifactId>
    <version>2.2.2</version>
</dependency>
<dependency>
    <groupId>commons-cli</groupId>
    <artifactId>commons-cli</artifactId>
    <version>1.2</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.3</version>
</dependency>
<dependency>
    <groupId>org.openoffice</groupId>
    <artifactId>juh</artifactId>
    <version>3.0.1</version>
</dependency>
<dependency>
    <groupId>org.openoffice</groupId>
    <artifactId>jurt</artifactId>
    <version>3.0.1</version>
</dependency>
<dependency>
    <groupId>org.openoffice</groupId>
    <artifactId>ridl</artifactId>
    <version>3.0.1</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-jdk14</artifactId>
    <version>1.5.6</version>
</dependency>
<dependency>
    <groupId>org.openoffice</groupId>
    <artifactId>unoil</artifactId>
    <version>3.0.1</version>
</dependency>
<dependency>
    <groupId>com.thoughtworks.xstream</groupId>
    <artifactId>xstream</artifactId>
    <version>1.3.1</version>
</dependency>