您的位置:首页 > 运维架构

FlexPaper+OpenOffice实现web的在线文档预览功能

2015-12-08 17:45 921 查看
一:准备工作

1.安装OpenOffice

2.下载FlexPaper

3.下载jodconverter

4.下载pinyin4j

5.下载swftools

二:相关代码

1.jsp页面

<%@ page import="com.fjrj.util.FlashUtil" %>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String path = request.getContextPath();

//String filePath=request.getParameter("filePath");
//String fileName=request.getParameter("fileName");
String filePath = "path";
String fileName="源文件.doc";

String applicationPath = application.getRealPath("");
String targetPath=applicationPath+"\\tempSwfFile";

String flashFile = null;
boolean flag = FlashUtil.copySourceFileToTarget(filePath, fileName, targetPath);

if(flag){
flashFile = new FlashUtil().beginConvert(targetPath,fileName);//绝对路径 相对路径
}

%>
<html>
<head>
<title>在线文档浏览</title>
<style type="text/css" media="screen">
html, body { height:100%; }
body { margin:0; padding:0; overflow:auto; }
</style>
<script type="text/javascript" src="<%=path%>/script/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="<%=path%>/script/js/flexpaper_flash.js"></script>
</head>
<body>
<div style="position:absolute;left:0px;top:0px;width:100%;height:100%;">
<a id="viewerPlaceHolder" style="width:100%;height:100%;display:block"></a>
<script type="text/javascript">
var fp = new FlexPaperViewer(
'FlexPaperViewer',
'viewerPlaceHolder', { config : {
SwfFile : escape('<%=path%>/tempSwfFile/<%=flashFile%>'), //此处为项目中的地址
Scale : 0.6,
ZoomTransition : 'easeOut',
ZoomTime : 0.5,
ZoomInterval : 0.2,
FitPageOnLoad : true,
FitWidthOnLoad : false,
PrintEnabled : true,
FullScreenAsMaxWindow : false,
ProgressiveLoading : false,
MinZoomSize : 0.2,
MaxZoomSize : 5,
SearchMatchAll : false,
InitViewMode : 'Portrait',

ViewModeToolsVisible : true,
ZoomToolsVisible : true,
NavToolsVisible : true,
CursorToolsVisible : true,
SearchToolsVisible : true,

localeChain: 'zh_CN'
}});
</script>

</div>
</body>
</html> 2.FlashUtil.java
package com.fjrj.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;

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 FlashUtil {

public static void main(String[] args){
String outPath = new FlashUtil().beginConvert("","附件.pdf");
System.out.println("生成swf文件:" + outPath);
// boolean outPath = new FlashUtil().isExistFlash("123.pdf");
// System.out.println("是否存在swf文件:" + outPath);
}
private static final String DOC = ".doc";
private static final String DOCX = ".docx";
private static final String XLS = ".xls";
private static final String XLSX = ".xlsx";
private static final String PDF = ".pdf";
private static final String SWF = ".swf";
private static final String TOOL = "pdf2swf.exe";

/**
* 入口方法-通过此方法转换文件至swf格式
* @param filePath 上传文件所在文件夹的绝对路径
* @param fileName 文件名称
* @return 生成swf文件名
*/
public String beginConvert(String filePath,String fileName) {
String outFile = "";
String fileNameOnly = "";
String fileExt = "";
if (null != fileName && fileName.indexOf(".") > 0) {
int index = fileName.indexOf(".");
fileNameOnly = fileName.substring(0, index);
fileExt = fileName.substring(index).toLowerCase();
}
String inputFile = filePath + File.separator + fileName;
String outputFile = "";
//如果是flash文件,直接显示
if(fileExt.equals(SWF)){
outFile = fileName;
}else {
//主要是针对中文汉字转拼音
fileNameOnly = new CnToSpell().getPinYin(fileNameOnly);
//如果存在对应的flash文件
boolean isExistFlash = isExistFlash(filePath,fileNameOnly);
if(isExistFlash){
outFile = fileNameOnly + SWF;
}else {
//如果是office文档,先转为pdf文件
if (fileExt.equals(DOC) || fileExt.equals(DOCX) || fileExt.equals(XLS)
|| fileExt.equals(XLSX)) {
outputFile = filePath + File.separator + fileNameOnly + PDF;
File pdfFile = new File(outputFile);
if(!pdfFile.exists()){//判断pdf文件是否已经生成
office2PDF(inputFile, outputFile);
}
inputFile = outputFile;
fileExt = PDF;
}
if (fileExt.equals(PDF)) {
outputFile = filePath + File.separator + fileNameOnly + SWF;
outputFile = outputFile.replace("\\","/");
File swfFile = new File(outputFile);
if(!swfFile.exists()){//判断swf文件是否已经生成
File parentFolder = swfFile.getParentFile();
if(parentFolder!=null&&!parentFolder.exists()){
parentFolder.mkdirs();
}
String toolFile = null;
if(filePath.indexOf("flexpaper")==-1){
toolFile = filePath + File.separator +"flexpaper"+ File.separator + TOOL;
}else{
toolFile = filePath + File.separator + TOOL;
}
convertPdf2Swf(inputFile, outputFile, toolFile);
}
outFile = fileNameOnly + SWF;
}
}
}
return outFile;
}

/**
* 将pdf文件转换成swf文件
* @param sourceFile pdf文件绝对路径
* @param outFile swf文件绝对路径
* @param toolFile 转换工具绝对路径
*/
private void convertPdf2Swf(String sourceFile, String outFile,
String toolFile) {
String command = toolFile + " \"" + sourceFile + "\" -o \"" + outFile
+ "\" -s flashversion=9 ";
try {
Process process = Runtime.getRuntime().exec(command);
System.out.println(loadStream(process.getInputStream()));
System.err.println(loadStream(process.getErrorS
4000
tream()));
System.out.println(loadStream(process.getInputStream()));
System.out.println("###--Msg: swf 转换成功");
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 检测文件夹下是否已存在对应的flash文件
* @return
*/
private boolean isExistFlash(String filePath,String fileNameOnly){
String fileName = fileNameOnly.substring(fileNameOnly.lastIndexOf("/")+1);
String newFilePath = fileNameOnly.substring(0 ,fileNameOnly.lastIndexOf("/")+1);
File file = new File(filePath + File.separator+newFilePath);
if(!file.exists()){//判断是否已经生成新文件夹,然后再去判断文件夹是否存在对应的flash文件
return false;
}
File[] files = file.listFiles();
for(int j=0;j<files.length;j++){
if(files[j].isFile()){
String filesName = files[j].getName();
if(filesName.indexOf(".")!=-1){
if(SWF.equals(filesName.substring(filesName.lastIndexOf(".")).toLowerCase())){
if(fileName.equals(filesName.substring(0,filesName.lastIndexOf(".")))){
return true;
}
}
}
}
}
return false;
}

/**
* office文档转pdf文件
* @param sourceFile office文档绝对路径
* @param destFile pdf文件绝对路径
* @return
*/
private int office2PDF(String sourceFile, String destFile) {
//OpenOfficeProperty porperty = (OpenOfficeProperty)BeanUtil.getBean(req,"OpenOfficeProperty");
String OpenOffice_HOME = "C:\\Program Files (x86)\\OpenOffice 4";
String host_Str = "127.0.0.1";
String port_Str = "8100";
try {
File inputFile = new File(sourceFile);
if (!inputFile.exists()) {
return -1; // 找不到源文件
}
// 如果目标路径不存在, 则新建该路径
File outputFile = new File(destFile);
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}
// 启动OpenOffice的服务
String command = OpenOffice_HOME
+ "\\program\\soffice.exe -headless -accept=\"socket,host="
+ host_Str + ",port=" + port_Str + ";urp;\"";
System.out.println("###\n" + command);
Process pro = Runtime.getRuntime().exec(command);
// 连接openoffice服务
OpenOfficeConnection connection = new SocketOpenOfficeConnection(
host_Str, Integer.parseInt(port_Str));
connection.connect();
// 转换
DocumentConverter converter = new OpenOfficeDocumentConverter(
connection);
converter.convert(inputFile, outputFile);

// 关闭连接和服务
connection.disconnect();
pro.destroy();

return 0;
} catch (FileNotFoundException e) {
System.out.println("文件未找到!");
e.printStackTrace();
return -1;
} catch (ConnectException e) {
System.out.println("OpenOffice服务监听异常!");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}

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

public static boolean copySourceFileToTarget(String sourcePath,String sourceName,String TargetPath){
String srcFileName=sourcePath+File.separator+sourceName;
String destFileName=TargetPath+File.separator+sourceName;
return copyFile(srcFileName, destFileName, false);
}

/**
* 复制单个文件
*
* @param srcFileName
* 待复制的文件名
* @param descFileName
* 目标文件名
* @param overlay
* 如果目标文件存在,是否覆盖
* @return 如果复制成功返回true,否则返回false
*/
public static boolean copyFile(String srcFileName, String destFileName,
boolean overlay) {
File srcFile = new File(srcFileName);
// 判断源文件是否存在
if (!srcFile.exists()) {
System.out.println("源文件:" + srcFileName + "不存在!");
return false;
} else if (!srcFile.isFile()) {
System.out.println("复制文件失败,源文件:" + srcFileName + "不是一个文件!");
return false;
}
// 判断目标文件是否存在
File destFile = new File(destFileName);
if (destFile.exists()) {
// 如果目标文件存在并允许覆盖
if (overlay) {
// 删除已经存在的目标文件,无论目标文件是目录还是单个文件
new File(destFileName).delete();
}else {
System.out.println("复制文件失败,目标文件"+destFileName+"已经存在");
return true;
}
} else {
// 如果目标文件所在目录不存在,则创建目录
if (!destFile.getParentFile().exists()) {
// 目标文件所在目录不存在
if (!destFile.getParentFile().mkdirs()) {
// 复制文件失败:创建目标文件所在目录失败
return false;
}
}
}
// 复制文件
int byteread = 0; // 读取的字节数
InputStream in = null;
OutputStream out = null;

try {
in = new FileInputStream(srcFile);
out = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];

while ((byteread = in.read(buffer)) != -1) {
out.write(buffer, 0, byteread);
}
return true;
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
} finally {
try {
if (out != null)
out.close();
if (in != null)
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

} 3.CnToSpell.java
package com.fjrj.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
*/
public class CnToSpell {

public String getPinYin(String src) {
char[] t1 = null;
t1 = src.toCharArray();
String[] t2 = new String[t1.length];
// 设置汉字拼音输出的格式
HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
t3.setVCharType(HanyuPinyinVCharType.WITH_V);
String t4 = "";
int t0 = t1.length;
try {
for (int i = 0; i < t0; i++) {
// 判断是否为汉字字符
if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {
t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);// 将汉字的几种全拼都存到t2数组中
t4 += t2[0];// 取出该汉字全拼的第一种读音并连接到字符串t4后
} else {
// 如果不是汉字字符,直接取出字符并连接到字符串t4后
t4 += Character.toString(t1[i]);
}
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
if(t4.indexOf("【")!=-1){
t4 = t4.replace("【","[");
}
if(t4.indexOf("】")!=-1){
t4 = t4.replace("】","]");
}
if(t4.indexOf("(")!=-1){
t4 = t4.replace("(","(");
}
if(t4.indexOf(")")!=-1){
t4 = t4.replace(")",")");
}
return t4;
}

public String getPinYinHeadChar(String str) {
String convert = "";
for (int j = 0; j < str.length(); j++) {
char word = str.charAt(j);
// 提取汉字的首字母
String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
if (pinyinArray != null) {
convert += pinyinArray[0].charAt(0);
} else {
convert += word;
}
}
return convert;
}

public String getCnASCII(String cnStr) {
StringBuffer strBuf = new StringBuffer();
// 将字符串转换成字节序列
byte[] bGBK = cnStr.getBytes();
for (int i = 0; i < bGBK.length; i++) {
strBuf.append(Integer.toHexString(bGBK[i] & 0xff));
}
return strBuf.toString();
}

public static void main(String[] args) {
CnToSpell cnToSpell = new CnToSpell();
String cnStr = "中华人民共和国(A-C)(12)_12345";
System.out.println(cnToSpell.getPinYin(cnStr));
System.out.println(cnToSpell.getPinYinHeadChar(cnStr));
System.out.println(cnToSpell.getCnASCII(cnStr));
}
}

实现:在不改变原先的功能基础上,增加预览功能。

效果图:


注:

1.可将启动openoffice的服务配置置于配置文件中,方便修改

2.FlexPaperViewer.swf文件要置于当前的jsp页面目录下
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: