Fork me on GitHub

Java实现office文档与pdf文档的在线预览功能

      最近项目有个需求要java实现office文档与pdf文档的在线预览功能,刚刚接到的时候就觉得有点难,以自己的水平难以在三四天做完。压力略大。后面查找百度资料、以及在同事与网友的帮助下,四天多把它做完。查找资料发现我们要实现的过程就是把office转换成pdf,当然pdf就不用转换了。然后在pdf转换为swf文件,在浏览器实现预览swf文件。整个过程就是这样,看起来很简单,实际操作起来会出现各种问题。下面我就把自己写的这一小功能记录下来。

1、首先我们需要找到可以把office转换成pdf的方法,查找资料发现有openoffice这一软件可以把office转换成pdf,这一软件先下载下来,然后记住自己安装的在那个位置。然后在cmd环境下进入安装目录的program目录,输入打开openoffice的命令:

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

输入完成之后在任务管理器可以看见soffice.bin的进程在任务管理器,这一服务就启动成功。当然在代码中转换office2pdf我们还需要一些架包。下载jodconverter-2.2.2架包,然后复制到lib目录下,引入架包就可以了。这个架包有如下包:

 

有一些项目重复的可以删除,根据实际情况自己处理。

 

2、我们需要找到转换pdf2swf的方法。查找资料发现swftools这个软件可以把pdf转换成swf文件。把它下下来安装好就可以了。

 

3、我们需要一个展示swf文件的容器,发现有flexpaper这个插件。而且展示效果还不错。所以我们需要下载这个插件。使用这个插件需要有三个js文件。分别是:jquery.jsflexpaper_flash.jsflexpaper_flash_debug.js。插件的名字是FlexPaperViewer.swf

 

整个项目结如下:

准备工作完成下面开始编码.

转换类为DocConverter 的代码:

 

package com.cectsims.util;

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;


/**
 * doc docx格式转换 
 */
public class DocConverter {
	private static final int environment = 1;// 环境 1:Windows 2:Linux
	private String fileString;// (只涉及PDF2swf路径问题)
	private String outputPath = "";// 输入路径 ,如果不设置就输出在默认 的位置
	private String fileName;
	private File pdfFile;
	private File swfFile;
	private File docFile;

	public DocConverter(String fileString) {
		ini(fileString);
		System.out.println("文件路径"+fileString);
	}

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

	/**
	 *  * 初始化 
	 * 
	 * @param fileString
	 *           
	 */
	private void ini(String fileString) {
		this.fileString = fileString;
		fileName = fileString.substring(0, fileString.lastIndexOf("."));
		docFile = new File(fileString);
		pdfFile = new File(fileName+ ".pdf");
		swfFile = new File(fileName+ ".swf");
	}

	/**
	 *  转为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 */
	@SuppressWarnings("unused")
	private void pdf2swf() throws Exception {
		Runtime r = Runtime.getRuntime();
		if (!swfFile.exists()) {
			if (pdfFile.exists()) {
				if (environment == 1) {// windows环境处理
					try {
						Process p = r.exec("D:/Program/swfttools/pdf2swf.exe "+ 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 (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();
	}

	/**
	 * * 转换主方法
	 */
	@SuppressWarnings("unused")
	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;
		}
		System.out.println("文件存在吗?"+swfFile);
		if (swfFile.exists()) {
			System.out.println("存在");
			return true;
		} else {
			System.out.println("不存在");
			return false;
		}
	}

	/**
	 *返回文件路径      
	 * @param     
	 */
	public String getswfPath(){
		if (this.swfFile.exists()){
			String tempString = swfFile.getPath();
			tempString = tempString.replaceAll("\\\\", "/");
			System.out.println("最后文件路径为"+tempString);
			return tempString;
		} else {
			return "文件不存在";
		}
	}

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

 

  

调用转换类只需要传wordpttexcelpdf文件所在的路径参数就可以了。

展示在线预览的jsp代码如下:

 

<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
   String swfFilePath=session.getAttribute("swfpath").toString();
   System.out.println("展示路径"+swfFilePath);
 %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html;charset=UTF-8" http-equiv="Content-Type">
<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>
<!--  <script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="js/flexpaper.js"></script>
<script type="text/javascript" src="js/flexpaper_handlers.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="width: 820px;height: 650px;display: block;"></a>
          <script type="text/javascript">
           var fp=new FlexPaperViewer('FlexPaperViewer','viewerPlaceHolder',{config:{SwfFile:escape('<%=swfFilePath%>'),Scale:1.2,
            ZoomTransition:'easeOut',ZoomTime:0.5,ZoomInterval:0.2,FitPageOnLoad:false,FitWidthOnload:false,
            FullScreenAsMaxWindow:false,ProgressiveLoading:false,MinZoomSize:0.2,MaxZoomSize:5,SearchMatchAll:false,
            InitViewMode:'SinglePage',RenderingOrder : 'flash',ViewModeToolsVisible:true,ZoomToolsVisible:true,NavToolsVisible:true,CursorToolsVisible:true,
            SearchToolsVisible:true,localeChain:'en_US'}});
          </script>
   </div>
</body>
</html>

 

其中可能会出现在线预览只能实现10页的情况,需要把RenderingOrder : 'flash',设置为flash才可以实现超过10页的在线预览。swfFilePat为转换后的文件所在路径。

转换后面的效果如下:

注意问题:

1、发现错误一般是openoffice服务没有开启。

2、Linux环境下会存在中文乱码的问题,是linux下不像windows支持那么多字体,需要安装多的字体,并且把字体所在位置链接到flexpaper所在位置。在使用pdf2swf加上参数-s languagedir=/usr/local/xpdf-chinese-simplified/。具体的一些参数请百度。

源代码已经在我的github上了,可以访问https://github.com/liaowp/OnlinePreview,也可以点击我博客的github标签。

如果有问题可以加QQ群咨询。178737461

 

posted @ 2015-08-28 19:21  鹏&鹏  阅读(62220)  评论(9编辑  收藏  举报