Java+FlexPaper+swfTools 文档在线预览demo

1.概述

主要原理

1.通过第三方工具openoffice,将word、excel、ppt、txt等文件转换为pdf文件

2.通过swfTools将pdf文件转换成swf格式的文件

3.通过FlexPaper文档组件在页面上进行展示

2.安装包下载

1.openoffice是Apache下的一个开放免费的文字处理软件

   下载地址:Apache oppenoffice 官网下载 版本-3.4.1

2.SWFTools是一组用来处理Flash的swf文件的工具包,我们使用它将pdf文件转成swf文件!

   下载地址:链接: http://pan.baidu.com/s/1pLL8oL9  密码d2bf

3.FlexPaper是一个开源轻量级的在浏览器上显示各种文档的组件

   下载地址:链接: http://pan.baidu.com/s/1kUONYBH 密码: ueqi

4.JODConverter一个Java的OpenDocument 文件转换器,在此我们只用到它的jar包

   下载地址:链接: http://pan.baidu.com/s/1bZpGkQ 密码: iiyw

3.安装文件

1.将所下载的文件(JODConverter除外)进行安装,盘符可随自己设定!需要注意的是在openoffice安装完成后,当我们使用它时,需将它的服务打开。在次我们需要以命令的方式打开:

打开dos窗口,进入openoffice安装盘符,输入以下代码来启动服务:

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

注意最后一个命令前边的‘—’,可不要写错!服务起不来,项目可是继续不下去的哦.

3.开发过程

1.新建项目,将flexpaper文件中的js文件夹(包含了flexpaper_flash_debug.js,flexpaper_flash.js,jquery.js,这三个js文件主要是预览swf文件的插件)拷贝至网站根目录;将FlexPaperViewer.swf拷贝至网站根目录下(该文件主要是用在网页中播放swf文件的播放器),目录结构如下图:

2.创建docUploadConvertLocalAction.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%@page import="java.io.*"%>
<%@page import="java.util.Enumeration"%>
<%@page import="com.oreilly.servlet.MultipartRequest"%>
<%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@page import="com.estone.test.DocConverterLocal"%>
<!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>Insert title here</title>
<style>
	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 class="title"style="margin-left: 50%">
	    	查看本地文件	
	    </div>
	<div>
		<form name="viewForm" id="form_swf" action="documentlocalView.jsp" method="POST" style="margin-left: 50%">
			<input type='submit' value='预览' class='BUTTON SUBMIT'/>
		</form>
	</div>
</body>
</html>

  

3.创建documentlocalView.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@page import="java.io.*"%>
<%@page import="java.util.Enumeration"%>
<%@page import="com.oreilly.servlet.MultipartRequest"%>
<%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@page import="com.estone.test.DocConverterLocal"%>

<%@page import="com.estone.test.DocConverter"%>

<%
	//本地文件地址
	String filenames = "D:\SC\Tool\dizhi\sql.txt"; //文件地址

	String converfilename = filenames.replaceAll("\\", "/");
	System.out.println(converfilename);

	DocConverter d = new DocConverter(converfilename);
	//调用conver方法开始转换,先执行doc2pdf()将office文件转换为pdf;再执行pdf2swf()将pdf转换为swf;
	d.conver();
	//调用getswfPath()方法,打印转换后的swf文件路径         FlexPaper+OpenOffice+SWFTools
	System.out.println(d.getswfPath());

	String ss = "dizhi";
	String swfpath = "upload" + "/" + ss
			+ d.getswfPath().substring(d.getswfPath().lastIndexOf("/"));

	String swfFilePath = swfpath;//获取swf存放的地址
%>
<!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="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>
<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=" 820px; height: 650px; display: block"></a>
		<script type="text/javascript"> 
				var fp = new FlexPaperViewer(	
						 'FlexPaperViewer',
						 'viewerPlaceHolder', { config : {
						 SwfFile : escape('<%=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 : 'en_US'
						}
					});
		</script>
	</div>
</body>
</html>

  

3.创建DocConverterLocal.java

package com.estone.test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
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 DocConverterLocal {

	/*
	 * 通过第三方工具openoffice,将word、excel、ppt、txt等文件转换为pdf文件
	 * 通过swfTools将pdf文件转换成swf格式的文件 通过FlexPaper文档组件在页面上进行展示
	 */

	private String SWFTools_Windows = "D:/D/D2/FZ/SwfTools(swf转换工具)/pdf2swf.exe ";

	private String fileString = "";
	private String outputPath = "";// 输入路径,如果不设置就输出在默认位置
	private String fileName;
	private File pdfFile;
	private File swfFile;
	private File docFile;
	private File odtFile;

	/*
	 * 初始化 @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; // fileName 文件地址+文件名,没有格式
			// 用于处理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");
				this.copyFile(docFile, pdfFile);
			} else {
				pdfFile = new File(fileName + ".pdf");
			}
			swfFile = new File(fileName + ".swf");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @Title: copyFile
	 * @Description: TODO
	 * @param: @param docFile2
	 * @param: @param odtFile2
	 * @return: void
	 * @throws
	 */
	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) {
					// 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
	 */
	@SuppressWarnings("unused")
	private void pdf2swf() throws Exception {
		Runtime r = Runtime.getRuntime();
		if (!swfFile.exists()) {
			if (pdfFile.exists()) {
				try {
					// 这里根据SWFTools安装路径需要进行相应更改
					Process p = r.exec(SWFTools_Windows + 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 {
				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;
		}

		try {
			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 "";
		}
	}

	/*
	 * 设置输出路径
	 */
	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");
			}
		}
	}

}

  

4.部署发布

启动tomcat,部署当前web应用

地址栏输入http://localhost:8080/ctcesimslocal/docUploadConvertLocalAction.jsp如下图:

 源码下载  链接: http://pan.baidu.com/s/1pKLsa0b 密码: 3v3q

原文地址:https://www.cnblogs.com/wusx/p/5614678.html