仿百度文库在线浏览文档

问题出现及解决思路   

遇到一个问题,要求能在线浏览doc、ppt、txt、excel等文档,于是就想到了百度文库的做法。上网搜了搜,总结出了一中做法,我用的是flexpager 插件。因为flexpager 用来显示swf格式的文件,但是文档又不能直接转化为swf文件。所以思路也就是先把文档转化为pdf格式,然后将pdf格式转为swf格式。

废话不多说,直接上实例。

工程结构

utils包下的三个工具类

获取路径工具类

package utils;

import java.io.File;
import java.net.URISyntaxException;

public class PathUtil {
	/**
	 * @return 获取web-info目录
	 */
	public static String getWEBINFDir() {
		String path = null;
		try {
			path = PathUtil.class.getResource("").toURI().getPath();
			path = path.substring(0, path.indexOf("classes"));
			return path;
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 
	 * @return WebRoot目录的绝对路径
	 */
	public static String getWebRootDir() {
		String path = null;
		String folderPath = PathUtil.class.getProtectionDomain().getCodeSource()
				.getLocation().getPath();
		if (folderPath.indexOf("WEB-INF") > 0) {
			path = folderPath.substring(0, folderPath
					.indexOf("WEB-INF/classes"));
		}
		path = path.replaceAll("%20", " ");
		return path;
	}
	
	/**
	 * @param args
	 */
	public static String getWebRootDirFilePath(String dir){
		String path = getWebRootDir()  + dir;
		File file = new File(path);
		if(! file.exists()){
			file.mkdirs();
		}
		return path;
	}

	/**
	 * @param args
	 */
	public static String getWebInfoDirFilePath(String dir){
		String path = getWEBINFDir()  + dir;
		File file = new File(path);
		if(! file.exists()){
			file.mkdirs();
		}
		return path;
	}
	
	
}
将office文档转化为pdf格式文件工具类

package utils;

import java.io.File;

import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeException;
import org.artofsolving.jodconverter.office.OfficeManager;

/**
 * @author Administrator
 *
 */
public class Office2PdfUtil {
	public static enum STATUS {
		SUCCESS, FAIL, NOINSTALL
	};
	private static OfficeManager officeManager;
	private static String OFFICE_HOME = "C:\\Program Files (x86)\\OpenOffice 4";
	private static int port[] = { 8100,8110,8120 };

	public static STATUS convert2PDF(File inputFile, File pdfFile) {
		try {
			startService();
			OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
			converter.convert(inputFile, pdfFile);
		} catch (OfficeException e) {
			return STATUS.NOINSTALL;
		}finally{
			stopService();
		}

		if (pdfFile.exists()) {
			return STATUS.SUCCESS;
		} else {
			return STATUS.FAIL;
		}

	}


	public static void startService() {
		DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
		try {
			//System.out.println("准备启动服务....");
			configuration.setOfficeHome(OFFICE_HOME);// 设置OpenOffice.org安装目录
			configuration.setPortNumbers(port); // 设置转换端口,默认为8100
			configuration.setMaxTasksPerProcess(3);//设置�?��进程�?
			configuration.setTaskExecutionTimeout(1000 * 60 * 3L);// 设置任务执行超时�?分钟
			configuration.setTaskQueueTimeout(1000 * 60 * 60 * 24L);// 设置任务队列超时�?4小时
			officeManager = configuration.buildOfficeManager();
			officeManager.start(); // 启动服务
			System.out.println("office转换服务启动成功!");
		} catch (Exception ce) {
			System.out.println("office转换服务启动失败!详细信息:" + ce);
		}
	}


	public static void stopService() {
		System.out.println("关闭office转换服务....");
		if (officeManager != null) {
			officeManager.stop();
		}
		System.out.println("关闭office转换成功!");
	}


}

将pdf转化为swf文件工具类

package utils;

import java.io.File;
import java.io.IOException;

public class Pdf2SwfUtil {

	private static String PDF2SWF_PATH = "D:\\SWFTools\\pdf2swf.exe";

	public static boolean convert2SWF(File pdfFile, File swfFile){
		if(!pdfFile.getName().endsWith(".pdf")){
			System.out.println("文件格式非PDF!");
			return false;
		}
		if(!pdfFile.exists()){
			System.out.println("PDF文件不存在!");
			return false;
		}
		if(swfFile.exists()){
			System.out.println("SWF文件已存在!");
			return true;
		}
		String command = PDF2SWF_PATH +" \""+pdfFile.getAbsolutePath()+"\" -o "+swfFile.getAbsolutePath()+" -T 9 -f";
		try {
			System.out.println("开始转换文档: "+pdfFile.getName());
			Runtime.getRuntime().exec(command);
			System.out.println("成功转换为SWF文件!");
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("转换文档为swf文件失败!");
			return false;
		}
	}
	
	public static boolean convert2SWF(String inputFile, String swfFile) {
		File pdfFile = new File(inputFile);
		File outFile = new File(swfFile);
		if(!inputFile.endsWith(".pdf")){
			System.out.println("文件格式非PDF!");
			return false;
		}
		if(!pdfFile.exists()){
			System.out.println("PDF文件不存在!");
			return false;
		}
		if(outFile.exists()){
			System.out.println("SWF文件已存在!");
			return false;
		}
		String command = PDF2SWF_PATH +" \""+inputFile+"\" -o "+swfFile+" -T 9 -f";
		try {
			System.out.println("开始转换文档: "+inputFile);
			Runtime.getRuntime().exec(command);
			System.out.println("成功转换为SWF文件!");
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("转换文档为swf文件失败!");
			return false;
		}
		
	}
}

Serverlet类

package servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import utils.Office2PdfUtil;
import utils.PathUtil;
import utils.Pdf2SwfUtil;

public class OnlineConvertServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public OnlineConvertServlet() {
		super();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}
	
	/**
	 * 转换doc文件并显示到页面上
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	
		//1.取得doc文件
		String docPath = PathUtil.getWebRootDirFilePath("doc") + "/bbb.txt";
		File docFile = new File(docPath);
		if(docFile.exists()){
			//2.装换为pdf文件
			String pdfPath = PathUtil.getWebRootDirFilePath("pdf") + "/aa.pdf";
			
			//"D:/workspace/bo/WebRoot/pdf/aa.pdf";
			File pdfFile = new File(pdfPath);
			if(pdfFile.exists())//pdf文件存在则删除
				pdfFile.delete();
			//转换
			Office2PdfUtil.convert2PDF(docFile, pdfFile);
			if(pdfFile.exists()){
				//3.转换为swf文件
				String swfPath = PathUtil.getWebRootDirFilePath("swf") + "/aa.swf";
				
				/*String swfPath = "D:/workspace/OnlineBrowsen/WebRoot/swf/aa.swf";*/
				File swfFile = new File(swfPath);
				if(swfFile.exists())
					swfFile.delete();
				boolean bl = Pdf2SwfUtil.convert2SWF(pdfFile, swfFile);	
				if(bl){
					response.setContentType("text/json;charset=utf-8");
					response.setContentType("application/json-rpc");
					response.setCharacterEncoding("utf-8");
					PrintWriter out = response.getWriter();
					String s = "{\"path\":\"aa.swf\"}";//把要浏览的文件地址返回到前台
					out.print(s);
					out.flush();
					out.close();
				}
			}
		}else{
			Logger.getLogger(OnlineConvertServlet.class).warn("要转换的doc文件不存在");
		}
	}
}

Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	id="WebApp_ID" version="3.1">
	<display-name>online_browsen</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	
	<servlet>
		<servlet-name>OnlineConvertServlet</servlet-name>
		<servlet-class>servlet.OnlineConvertServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>OnlineConvertServlet</servlet-name>
		<url-pattern>/OnlineConvertServlet.do</url-pattern>
	</servlet-mapping>

</web-app>

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
<style type="text/css" media="screen">
html,body {
	height: 100%;
}

body {
	margin: 0;
	padding: 0;
	overflow: auto;
}
</style>
<script type="text/javascript">
		var basePath = "<%=basePath%>";
	</script>
<script type="text/javascript" src="js/jquery1.7.1.min.js"></script>
<script type="text/javascript" src="js/flexpaper_flash.js"></script>

</head>

<body>

	<div style="position:absolute;left:110px;top:10px;">
		<input type="button" value="显示Paper" οnclick="viewFlexPaper()" />
	</div>

	<div style="position:absolute;left:110px;top:30px;">
		<a id="viewerPlaceHolder" 	style="width:720px;height:600px;display:block"></a>
		<script type="text/javascript"> 
	         var fpv = new FlexPaperViewer(	
        			 basePath + 'flexpager/FlexPaperViewer',
					 'viewerPlaceHolder', { config : {
					 SwfFile : escape(basePath + "swf/aa.swf"),//要浏览的swf文件
					 Scale : 0.9, // 初始化缩放比例,参数值应该是大于零的整数
					 ZoomTransition : 'easeOut',//Flexpaper中缩放样式   easenone, easeout, linear, easeoutquad
					 ZoomTime : 0.5,//从一个缩放比例变为另外一个缩放比例需要花费的时间,该参数值应该为0或更大。
					 ZoomInterval : 0.2,//缩放比例之间间隔,默认值为0.1,该值为正数。
					 FitPageOnLoad : true,// 初始化得时候自适应页面,与使用工具栏上的适应页面按钮同样的效果。
					 FitWidthOnLoad : false,//初始化的时候自适应页面宽度,与工具栏上的适应宽度按钮同样的效果。
					 FullScreenAsMaxWindow : true,//全屏
					 ProgressiveLoading : false,//当设置为true的时候,展示文档时不会加载完整个文档,而是逐步加载,但是需要将文档转化为9以上的flash版本(使用pdf2swf的时候使用-T 9 标签)。
					 MinZoomSize : 0.2,//设置最小的缩放比例。
					 MaxZoomSize :2,// 最大的缩放比例。
					 SearchMatchAll : false,//设置为true的时候,单击搜索所有符合条件的地方高亮显示。
					 InitViewMode : 'Portrait',//设置启动模式如"Portrait" or "TwoPage".
					 PrintPaperAsBitmap : false,// 以位图的形式打印页面
					 
					 ViewModeToolsVisible : false,//工具栏上是否显示样式选择框。
					 ZoomToolsVisible : true,//工具栏上是否显示缩放工具。
					 NavToolsVisible : true,//工具栏上是否显示导航工具。
					 CursorToolsVisible : true,//工具栏上是否显示光标工具。
					 SearchToolsVisible : true,//工具栏上是否显示搜索。
						
					 localeChain: 'zh_CN' //设置地区(语言)
				}});
	         function viewFlexPaper(){
	        		$.ajax({
	        			url:basePath + "/OnlineConvertServlet.do",
	        			type: "POST",
	        			dataType: "json",
	        			data:{"id":500},
	        			success: function(data){
	        				if(data){
	        					var path = basePath + "swf/" + data.path;
	        					$FlexPaper().loadSwf(path);
	        				}
	        			}
	        		});
	        	}
	        </script>
	</div>
</body>
</html>

代码就绪完毕。

在运行之前必须安装两个插件。Openoffice和SWFTools .在Utils工具类中的Office2PdfUtil和Pdf2SwfUtil中配置安装路径。因为转化时借助了这两个插件。

一切就绪后,即可运行完成。




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

野狼e族

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值