java+jsp 实现openoffice文档在线浏览
准备工作
1.安装openoffice swftools 下载FlexPaper
openoffice官网 download full installation
http://www.openoffice.org/zh-cn/download/
swftools官网 找linux/windows对应版本
http://www.swftools.org/download.html
FlexPaper下载
https://download.****.net/download/qq_35653822/10751115
2.启动配置openoffice swftools flexpaper
安装openoffice后 去program目录下执行(每次电脑重启都要执行)
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
program位置在你桌面图表右键属性(我当时就找了半天)
flexpaper放到你工程可以访问静态文件的一个文件夹下
3.写代码
参考博客
https://www.cnblogs.com/liaoweipeng/p/4767660.html
package com.trs.smas.util;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
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) {
try {
URL picUrl;
HttpURLConnection conn = null;
InputStream is = null;
picUrl = new URL(fileString);
conn = (HttpURLConnection) picUrl.openConnection();
conn.setConnectTimeout(20000);
conn.setReadTimeout(20000);
conn.connect();
is = conn.getInputStream();
String filename = fileString.substring(fileString.lastIndexOf("/")+1);
// fileName = filename.substring(0, filename.lastIndexOf("."));;
File folder = new File("F:/test/");
if(!folder.exists()){
folder.mkdir();
}
File file = new File("F:/test/"+filename);
OutputStream os = new FileOutputStream(file);
final int buffer_size = 1024;
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
os.close();
docFile = file;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
this.fileString = docFile.getPath();
fileName = this.fileString.substring(0, this.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("F:/UTIL/seeonline/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 "文件不存在";
}
}
public String getdocPath(){
if (this.docFile.exists()){
String tempString = docFile.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");
}
}
}
public static void main(String[] args) {
//fileName = “F:/2.docx”;
String ContextPath = "F:/UTIL/jiangchengV1.0.doc";//文件路径+文件名
DocConverter converter = new DocConverter(ContextPath);
converter.conver();
String getswfPath = converter.getswfPath();
System.out.println(getswfPath);
}
}
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String swfFilePath=(String)request.getAttribute("swfpath");//beforefile
String beforefile=(String)request.getAttribute("beforefile");
%>
<!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="<%=request.getContextPath() %>/scripts/FlexPaper/js/jquery.js"></script>
<script type="text/javascript" src="<%=request.getContextPath() %>/scripts/FlexPaper/js/flexpaper_flash.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> -->
<!-- <style>
[class*="span"] {
margin-left: 150px;
}
#documentTitle {
overflow: hidden;
table-layout: fixed;
word-break: break-all;
}
</style> -->
<title>在线文档预览</title>
<style>
[class*="span"] {
margin-left: 20px;
}
#documentTitle {
overflow: hidden;
table-layout: fixed;
word-break: break-all;
}
.download{
font-size:20px;
height:50px;
position:relative;
left:20%;
top:10px;
}
</style>
</head>
<body data-spy="scroll" data-target=".bs-docs-sidebar">
<div style="position: relative;left:20%;">
<a id="viewerPlaceHolder" style="width: 820px;height: 800px;display: block;"></a>
<script type="text/javascript">
var fp=new FlexPaperViewer('<%=request.getContextPath() %>/scripts/FlexPaper/FlexPaperViewer','viewerPlaceHolder',{config:{SwfFile:escape('http://localhost:8088/dpx/swffile/<%=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'}});
console.log(fp);
</script>
</div>
<td>
<a href="<%=request.getContextPath()%>/admin/personalized/download?filepath=<%=beforefile%>" class="download">下载附件</a>
</td>
</body>
</html>
中途遇到问题
1.jsp中flexpaper文件引入不进来 多半是FlexPaperViewer没写文件路径 或者flexpaper所在位置不是浏览器可访问路径
2.openoffice链接失败 没执行soffice那一行命令
3.不管用openoffice还是linux都访问不到生成的swf文件:没加 http://