1.转载自 : java实现附件预览(openoffice+swftools+flexpaper)
1.概述
主要原理
1.通过第三方工具openoffice,将word、excel、ppt、txt等文件转换为pdf文件
2.通过swfTools将pdf文件转换成swf格式的文件
3.通过FlexPaper文档组件在页面上进行展示
2.安装包下载
1.openoffice是Apache下的一个开放免费的文字处理软件
下载地址:Apache oppenoffice 官网下载 版本-3.4.1
2.SWFTools是一组用来处理Flash的swf文件的工具包,我们使用它将pdf文件转成swf文件!
下载地址:SWFTools官网下载 swftools-2013-04-09-1007.exe
3.FlexPaper是一个开源轻量级的在浏览器上显示各种文档的组件
在这里分享一下一位大哥的下载地址:FlexPaper所需文件,下载其中的 FlexPaper_1.5.1_flash.rar .如果失效了,也可以找我要
4.JODConverter一个Java的OpenDocument 文件转换器,在此我们只用到它的jar包
下载地址:JODCConverter下载
3.开启openoffice服务
1.切换到 openoffice安装目录下的program目录
cd C:\Program Files (x86)\OpenOffice 4\program
2.开启服务
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
4.开发
1,导入JODConverter的jar包,将以下的都导入,重复的可以删了
2.将FlexPaper文件夹导入到webapp下
3 。后台实现
创建转换类DocConverter.java
package com.bos.common;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* create by luojie 2018/8/10
*/
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);
}
public String getFileName() {
return this.fileName;
}
/**
* 重新设置file
*
* @param fileString
*/
public void setFile(String fileString) {
ini(fileString);
}
/**
* 初始化
*
* @param fileString
*/
private void ini(String fileString) {
this.fileString = fileString;
fileName = fileString.substring(fileString.lastIndexOf("/") + 1, fileString.lastIndexOf("."));
//此处我做了文件名转化,如果文件名包含中文,会报错。有空再去看看其他办法
Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
Matcher m = p.matcher(fileName);
if (m.find()) {
Date d = new Date();
fileName = String.valueOf(d.getTime());
}
docFile = new File(fileString);
pdfFile = new File(fileName + ".pdf");
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String tomcatRoot = request.getSession().getServletContext().getRealPath("/") + "swf/";
//生成的swf文件我是暂时放在taomcat里,因为放在其他位置无法加载,试了网上说的添加信任文件夹也不行...
swfFile = new File(tomcatRoot + fileName + ".swf");
}
/**
* 转为PDF
*/
private void doc2pdf() throws Exception {
if (docFile.exists()) {
if (!pdfFile.exists()) {
OpenOfficeConnection connection = new SocketOpenOfficeConnection();
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 (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 {
//此处要指定你机器安装的pdf2swf.exe全路径D:\ruanjian\gpdf2swf.exe
Process p = r.exec("D:/ruanjian/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;
}
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) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String tomcatRoot = request.getSession().getServletContext().getRealPath("/");
System.out.println(tomcatRoot);
this.outputPath = tomcatRoot + outputPath;
if (!outputPath.equals("")) {
String realName = fileName.substring(fileName.lastIndexOf("/") + 1,
fileName.length());
if (outputPath.charAt(outputPath.length()) == '/') {
swfFile = new File(outputPath + realName + ".swf");
} else {
swfFile = new File(outputPath + realName + ".swf");
}
}
}
}
控制层
@RequestMapping(value = "yulan")
public String yulan(){
String filePath ="c:/kaifa/a.doc";
DocConverter converter = new DocConverter(filePath);
converter.conver();
String getswfPath =converter.getFileName();
System.out.println(getswfPath);
model.addAttribute("url",getswfPath+".swf");
return "common/previewFile";
}
preview.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!-- saved from url=(0014)about:internet -->
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
html, body { height:100%; }
body { margin:0; padding:0; overflow:auto; }
#flashContent { display:none; }
</style>
<script type="text/javascript" src="<%=basePath%>/js/flexPaper/swfobject.js"></script>
<script type="text/javascript" src="<%=basePath%>/js/flexPaper/flexpaper_flash.js"></script>
<script type="text/javascript" src="<%=basePath%>/js/flexPaper/flexpaper_flash_debug.js"></script>
<script type="text/javascript">
// For version detection, set to min. required Flash Player version, or 0 (or 0.0.0), for no version detection. -->
var swfVersionStr = "0";
var xiSwfUrlStr = "playerProductInstall.swf";
var flashvars = {
//escape中指定的是你swf文件的路径
//SwfFile : escape("${pageContext.request.contextPath}/preview${url}"),
SwfFile : escape("${pageContext.request.contextPath}/swf/${url}"),
Scale : 0.6,
ZoomTransition : "easeOut",
ZoomTime : 0.5,
ZoomInterval : 0.1,
FitPageOnLoad : false,
FitWidthOnLoad : true,
PrintEnabled : true,
FullScreenAsMaxWindow : false,
ProgressiveLoading : true,
MinZoomSize : 0.2,
MaxZoomSize : 5,
PrintToolsVisible : false,
ViewModeToolsVisible : true,
ZoomToolsVisible : true,
FullScreenVisible : true,
NavToolsVisible : true,
CursorToolsVisible : true,
SearchToolsVisible : true,
localeChain: "en_US"
};
var params = {
}
params.quality = "high";
params.bgcolor = "#ffffff";
params.allowscriptaccess = "sameDomain";
params.allowfullscreen = "true";
var attributes = {};
attributes.id = "FlexPaperViewer";
attributes.name = "FlexPaperViewer";
//此处一定要指定你项目下的FlexPaperViewer.swf路径
swfobject.embedSWF("${pageContext.request.contextPath}/FlexPaper_1.5.1_flash/FlexPaperViewer.swf", "flashContent",
"800", "500",//指定高和宽
swfVersionStr, xiSwfUrlStr,
flashvars, params, attributes);
swfobject.createCSS("#flashContent", "display:block;text-align:left;");
</script>
</head>
<body>
<div style="position:absolute;left:10px;top:10px;">
<div id="flashContent">
<p>
To view this page ensure that Adobe Flash Player version
10.0.0 or greater is installed.
</p>
</div>
</div>
</body>
</html>
测试