JavaWeb实现office文件、PDF文件在线预览功能
实现思想介绍
文件上传的同时就做好文件处理。所有的文件交由服务器处理,避免客户端安装插件,数据库设计上要提供保存两个文件的存放地址的字段,一个是供给下载原件使用,另一个供给在线预览使用。
1、使用OpenOffice将office文件转成PDF文件
2、使用SwfTools将PDF等类型文件转成swf文件
使用插件(在服务器上下载并安装,紧记安装路径,后面会用到)
OpenOffice
- Apache_OpenOffice_4.1.6_Win_x86_install_zh-CN.exe
- 下载地址
SwfTools
- swftools-0.9.0.exe
- 下载地址
使用的jar
<!-- 在线预览office文件 start-->
<!-- https://mvnrepository.com/artifact/commons-cli/commons-cli -->
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.artofsolving/jodconverter -->
<dependency>
<groupId>com.artofsolving</groupId>
<artifactId>jodconverter</artifactId>
<version>2.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openoffice/juh -->
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>juh</artifactId>
<version>4.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openoffice/jurt -->
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>jurt</artifactId>
<version>4.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openoffice/ridl -->
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>ridl</artifactId>
<version>4.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-jdk14 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>1.7.25</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openoffice/unoil -->
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>unoil</artifactId>
<version>4.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.thoughtworks.xstream/xstream -->
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.3.1</version>
</dependency>
<!-- 在线预览office文件 end-->
注意jodconverter-2.2.1.jar版本不支持07版本以后的office文件,jodconverter-2.2.2.jar Maven仓库内没有,需要自己手动导入jar(将会在下面介绍如何导入)
前端页面所需要的JS
- flexpaper_flash.js
- flexpaper_flash_debug.js
- jquery-1.8.3.min.js
下载地址
jodconverter-2.2.2.jar下载
下载之后,解压开来的项目中就有jar包,直接复制出来即可
下载地址
也可以从我CSDN里面下载全部的插件以及手动导入的jar包
下载地址
后台代码实现
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
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;
/**
* <p>
* FileConverter.java 1、office文件转成PFD文件</dt> 2、PDF文件转成Swf文件</dt>
* </p>
*
* @since 2019年4月15日 上午11:13:36
* @author XinLau
* @version 1.0
*/
@SuppressWarnings("unused")
public class FileConverter {
private static final int environment = 1;// 环境 1:Windows 2:Linux
/**
* OpenOffice相关配置
*/
private static final String OpenOffice_HOME = "D:\\DevelopmentTools\\OpenOffice";
private static final String host_Str = "127.0.0.1";
private static final String port_Str = "8100";
/**
* SWFTools相关配置
*/
private static final String SWFTools_HOME = "D:/DevelopmentTools/SWFTools";
private String fileString;// (只涉及PDF2swf路径问题)
private String outputPath = "";// 输入路径 ,如果不设置就输出在默认 的位置
private String fileName;
private File pdfFile;
private File swfFile;
private File docFile;
public FileConverter(String fileString) {
ini(fileString);
System.out.println("文件路径" + fileString);
}
/**
* <p>
* setFile 重新设置file
* </p>
*
* @param fileString
* @return void
* @author XinLau
* @since 2019年4月15日上午11:33:46
*/
public void setFile(String fileString) {
ini(fileString);
}
/**
* <p>
* ini 初始化
* </p>
*
* @param fileString
* @return void
* @author XinLau
* @since 2019年4月15日上午11:34:03
*/
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");
}
/**
* <p>
* office2pdf 转为PDF
* </p>
*
* @throws Exception
* @return void
* @author XinLau
* @since 2019年4月15日上午11:34:44
*/
private void office2pdf() throws Exception {
if (docFile.exists()) {
if (!pdfFile.exists()) {
try {
// 启动OpenOffice的服务
String command = OpenOffice_HOME + "\\program\\soffice.exe -headless -accept=\"socket,host=" + host_Str
+ ",port=" + port_Str + ";urp;\"-nofirststartwizard";
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(docFile, pdfFile);
// 关闭连接和服务 close the connection
connection.disconnect();
pro.destroy();
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转换器异常,需要转换的文档不存在, 无法转换****");
}
}
/**
* <p>
* pdf2swf 转换成 swf,删除pdf文件
* </p>
*
* @throws Exception
* @return void
* @author XinLau
* @since 2019年4月15日上午11:35:31
*/
private void pdf2swf() throws Exception {
Runtime r = Runtime.getRuntime();
if (!swfFile.exists()) {
if (pdfFile.exists()) {
if (environment == 1) {// windows环境处理
try {
// 注意修改 SWFTools工具的安装路径
String processArdess = SWFTools_HOME + "/pdf2swf.exe " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9";
Long fileLength = pdfFile.length();
//processArdess = processArdess + " -s poly2bitmap";
Process p = r.exec(processArdess);
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已经存在不需要转换****");
}
}
/**
*
* <p>
* pdfConverterSwf pdf文件转成swf文件,保留pdf文件
* </p>
*
* @throws Exception
* @return void
* @author XinLau
* @since 2019年4月16日上午9:14:34
*/
public void pdfConverterSwf() throws Exception {
Runtime r = Runtime.getRuntime();
if (!swfFile.exists()) {
if (pdfFile.exists()) {
if (environment == 1) {// windows环境处理
try {
// 注意修改 SWFTools工具的安装路径
String processArdess = SWFTools_HOME + "/pdf2swf.exe " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9";
Long fileLength = pdfFile.length();
Process p = r.exec(processArdess);
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();
}
/**
* <p>
* conver 转换主方法
* </p>
*
* @return
* @return boolean
* @author XinLau
* @since 2019年4月15日上午11:36:32
*/
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 {
office2pdf();
pdf2swf();
//pdfConverterSwf();
} 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;
}
}
/**
* <p>
* getswfPath 返回文件路径
* </p>
*
* @return String
* @author XinLau
* @since 2019年4月15日上午11:37:17
*/
public String getswfPath() {
if (this.swfFile.exists()) {
String tempString = swfFile.getPath();
tempString = tempString.replaceAll("\\\\", "/");
System.out.println("最后文件路径为" + tempString);
return tempString;
} else {
return "文件不存在";
}
}
/**
* <p>
* setOutputPath 设置输出路径
* </p>
*
* @param outputPath
* @return void
* @author XinLau
* @since 2019年4月15日上午11:37:40
*/
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) {
String fileName = "D:\\DevelopmentTools\\apache-tomcat-7.0.86\\webapps\\property-web\\upload\\doc\\d881c0f6bfcf458fb826502177e02123.docx";
FileConverter fileConverter = new FileConverter(fileName);
try {
//fileConverter.pdf2swf();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
/*fileConverter.office2pdf();
String tempString = fileConverter.swfFile.getPath();
tempString = tempString.replaceAll("\\\\", "/");
System.out.println("最后文件路径为" + tempString);*/
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
boolean mark = fileConverter.conver();
String path = fileConverter.getswfPath();
System.out.println(path);
path = path.substring(path.lastIndexOf("/property-web"));
System.out.println(path);
}
}
前端展示页面
<%@page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String contextPath = request.getContextPath();
String onlinePreviewLocation = request.getParameter("onlinePreviewLocation");
%>
<!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="<%=contextPath %>/lib/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="<%=contextPath %>/js/util/flexpaper_flash.js"></script>
<script type="text/javascript" src="<%=contextPath %>/js/util/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: 50px; top: 10px;"> -->
<div>
<a id="viewerPlaceHolder" style="width: 100%; height: 100%; display: block;"></a>
<script type="text/javascript">
var afterUrl = window.location.search.substring(1);//(问号以后的字符串)
var afterEqual = afterUrl.substring(afterUrl.indexOf('=')+1);//.toUpperCase();//(等号以后的字符串,及你所要的参数)
console.log(afterEqual);
var host = window.location.host;
var port = window.location.port;
var onlinePreviewLocation = host + afterEqual
console.log(onlinePreviewLocation);
var fp = new FlexPaperViewer(
'FlexPaperViewer',
'viewerPlaceHolder', {
config: {
SwfFile: decodeURI('<%=onlinePreviewLocation%>'),
Scale: 1.2,
ZoomTransition: 'easeOut',
ZoomTime: 0.5,
ZoomInterval: 0.2,
FitPageOnLoad: false,
FitWidthOnload: false,
FullScreenAsMaxWindow: true,
ProgressiveLoading: false,
MinZoomSize: 0.2,
MaxZoomSize: 5,
SearchMatchAll: false,
InitViewMode: 'SinglePage',
RenderingOrder: 'flash',
ViewModeToolsVisible: true,
ZoomToolsVisible: true,
NavToolsVisible: true,
CursorToolsVisible: true,
SearchToolsVisible: true,
localeChain: 'zh_CN'
}
});
</script>
</div>
</body>
</html>