您的位置:首页 > 编程语言 > Java开发

Java+FlexPaper+swfTools仿百度文库文档在线预览系统设计与实现

2018-02-09 11:30 681 查看
       因项目需要实现文库的上传与在线阅读,因此在网上查找了一些资料,采用Java+FlexPaper+swfTools可以实现仿文库文档在线阅读。其实现过程如下:一、文档在线阅读思路
      1.用OpenOffice把PPT、Word、Excel、Text转换为pdf           2.用SWFTool将生成的pdf转换成swf,然后利用FlexPlayer实现在线预览播放
二、准备工作
      1.安装OpenOffice,官网下载地址:http://www.openoffice.org/download/index.html
      2.启动OpenOffice服务,CMD命令进入OpenOffice安装目录下的program目录,键入如下命令
      soffice "-accept=socket,host=localhost,port=8100;urp;StarOffice.ServiceManager" -nologo -headless -nofirststartwizard
     


  参考资料:http://blog.csdn.net/hbcui1984/article/details/5109169
       3.下载JODConverter:http://sourceforge.net/projects/jodconverter/files/,项目中主要使用lib目录下的jar包。
       4.下载并安装SWFTools:http://www.swftools.org/download.html,下载exe文件安装完成即可
       5.下载FlexPlayer:http://flexpaper.devaldi.com/download/
三、软件开发 
       1.新建web项目并引入jar包
       阅读JODConverter/lib目录下的DEPENDENCIES.txt可知需要添加哪些jar包      
       新建OfficeOnline项目,引入相应jar包(使用的是cos进行文档上传,cos.jar需要另外下载),将FlexPaper_1.5.1_flash.zip解压后的js目录引入到项目中,FlexPaperViewer.swf也引入进来  。         2.新建DocConverter.java
        注意:根据SWFTools安装路径不同需要修改pdf2swf()方法中pdf2swf.exe的路径,我安装的路径是在D盘
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
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 DocConverter {
private static final int environment = 1;// 环境1:windows,2:linux(涉及pdf2swf路径问题)
private String fileString;
private String outputPath = "";// 输入路径,如果不设置就输出在默认位置
private String fileName;
private File pdfFile;
private File pdfWaterFile;
private File swfFile;
private File docFile;

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

/*
* 重新设置 file @param fileString
*/
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");
pdfWaterFile = new File(fileName + "water.pdf");;
swfFile = new File(fileName + ".swf");
}

/*
* 转为PDF @param file
*/
public 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);
converter.convert(docFile, pdfWaterFile);
// 将pdf文件先加水印然后输出
// 要输出的pdf文件
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(pdfFile.getPath())));
WaterPrint wp = new WaterPrint();
wp.setWatermark(bos, pdfWaterFile.getPath(),null,16);
// close the connection
connection.disconnect();
if (pdfWaterFile.exists()) {
pdfWaterFile.delete();
}
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
*/
public void pdf2swf() throws Exception {
Runtime r = Runtime.getRuntime();
if (!swfFile.exists()) {
if (pdfFile.exists()) {
if (environment == 1)// windows环境处理
{
try {

/*
* 使用命令  C:\SWFTools\pdf2swf.exePaper.pdf-oPaper%.swf-f -T 9 -t -s storeallcharacters
-f  字体应该被嵌入,能够改善swf搜索
-T 9  设置转化的flash版本为9,提高swf的稳定性
-t   在每一帧时插入停止,提高swf的稳定性
-s storeallcharacters存储的文本文件中的所有字符信息,提高搜索能力
*/
// 这里根据SWFTools安装路径需要进行相应更改
Process p = r.exec("d:/Program Files (x86)/SWFTools/pdf2swf.exe " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9 -f");
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 if (environment == 2)// linux环境处理
{
try {
Process p = r.exec("pdf2swf " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9 -f");
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;
//把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****");
} else {
System.out.println("****swf转换器开始工作,当前设置运行环境linux****");
}

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");
}
}
}

public static void main(String s[]) {
DocConverter d = new DocConverter("E:/TDDOWNLOAD/test2.doc");
d.conver();
}
}
运行结果:


3.创建文档预览文件documentView.jsp(用于前端预览文档,路径为转换为转换后的swf文件路径)
<%@page import="org.apache.commons.lang3.StringUtils"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="com.common.util.*"%>
<%
String file_path = CommonUtil.getConfig("common","DOCUMENT_PATH");//获取文档存放的公共路径
 String swfFilePath=session.getAttribute("document_url").toString();//获取转换后存储在计算机硬盘的路径
 String swfPath = swfFilePath.substring(file_path.length(), swfFilePath.length());
StringBuffer url = request.getRequestURL();
String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();//获取访问的系统的域名或IP
String realpath=tempContextUrl+"upload"+swfPath;//新的访问路径(在Tomcat中server配置)
String FlexPaperViewer=tempContextUrl+"upload/FlexPaperViewer";//FlexPaperViewer.swf的路径(注意:FlexPaperViewer.swf要和上传文档生成的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="../static/js/ttdms/jquery.js"></script>   -->
<script type="text/javascript" src="../static/js/ttdms/flexpaper_flash.js"></script>
<script type="text/javascript" src="../static/js/ttdms/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:2%;top:2%;width:96%;height:96%;">
<a id="viewerPlaceHolder" style="width:98%;height:100%;display:block"></a>

<script type="text/javascript">

 var fp = new FlexPaperViewer(     
                         '<%=FlexPaperViewer%>',  //这里是FlexPaperViewer.swf的路径,相对根目录 
                         'viewerPlaceHolder',  //这里是要显示Swf的区域的ID
                         { config : { 
                        	/*  SwfFile : escape('http://192.168.1.139:8080/upload/16/32/admin/6e31927bd6d049cc86b18db7f3ecec79.swf'), */   
                         SwfFile : escape('<%=realpath%>'),   //这里是要显示的swf的位置                        
                         Scale : 0.6,  //缩放比例  
                         ZoomTransition : 'easeOut',  //Flexpaper中缩放样式,它使用和Tweener一样的样式,默认参数值为easeOut.其他可选值包括: easenone, easeot, linear, easeoutquad  
                         ZoomTime : 0.5,  //从一个缩放比例变为另外一个缩放比例需要花费的时间,该参数值应该为0或更大。
                         ZoomInterval : 0.2,  //缩放比例之间间隔,默认值为0.1,该值为正数
                         FitPageOnLoad : true,  //初始化的时候自适应页面,与使用工具栏上的适应页面按钮同样的效果。
                         FitWidthOnLoad : false,  //初始化的时候自适应页面宽度,与工具栏上的适应宽度按钮同样的效果。  
                         FullScreenAsMaxWindow : false,  //是否支持全屏,当设置为true的时候,单击全屏按钮会打开一个flexpaper最大化的新窗口而不是全屏,当由于flash播放器因为安全而禁止全屏,而使用flexpaper作为独立的flash播放器的时候设置为true是个优先选择。
                         ProgressiveLoading : false,  //当设置为true的时候,展示文档时不会加载完整个文档,而是逐步加载,但是需要将文档转化为9以上的flash版本(使//用pdf2swf的时候使用-T 9 标签)。
                         MinZoomSize : 0.2,  //最小的缩放比例。
                         MaxZoomSize : 5,  //设置最大的缩放比例。
                         SearchMatchAll : false,  //设置为true的时候,单击搜索所有符合条件的地方高亮显示。
                         InitViewMode : 'SinglePage',  //启动模式
                           
                         ViewModeToolsVisible : true, //工具栏上是否显示样式选择框(就是显示缩略图或分页显示的工具)   
                         ZoomToolsVisible : true,  //工具栏上是否显示缩放工具
                         NavToolsVisible : true,  //工具栏上是否显示导航工具(也就是页码工具)
                         CursorToolsVisible : true,  //工具栏上是否显示光标工具 
                         SearchToolsVisible : true,   //工具栏上是否显示搜索
                          
                         localeChain: 'zh_CN'   //语言
                         }});  
</script>
</div>
</body>
</html>

这样就可以实现文档的在线阅读功能了,其中运行结果如下:


注:TOMCAT中建虚拟目录,要在server.xml的host中添加context,如:<host><Context crossContext="true" docBase="E:/upload" path="/upload" reloadable="false"/></host>参考资料(博客):http://www.cnblogs.com/star-studio/archive/2011/12/09/2281807.htmlhttp://blog.csdn.net/hil2000/article/details/8459940
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: