仿百度文库在线浏览文档

问题出现及解决思路   

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

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

工程结构

仿百度文库在线浏览文档_第1张图片

仿百度文库在线浏览文档_第2张图片

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



	online_browsen
	
		index.html
		index.htm
		index.jsp
		default.html
		default.htm
		default.jsp
	
	
	
		OnlineConvertServlet
		servlet.OnlineConvertServlet
	
	
		OnlineConvertServlet
		/OnlineConvertServlet.do
	


index.jsp

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






My JSP 'index.jsp' starting page















	

代码就绪完毕。

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

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




你可能感兴趣的:(web后端,flexpager,在线浏览文档,仿百度文库)