Java中openoffice预览文件
1.开发准备
以前一直没有记录的习惯,从今天开始把自己的知识一点点的都积累起来,好了废话不多说了直接开始程序了。
1.你需要安装一个openoffice ,目前最新的版本是4.1.1 下载地址 http://www.openoffice.org/zh-cn/download/ ,下载下来直接安装,安装完成之后,你还需要启动openoffice的服务,在启动服务的时候你需要注意openoffice服务的安装路径,特别是在安装类型选择的时候,完整安装和自定义安装如果你选择的是完整安装那么程序默认的是"C:\Program Files (x86)" 下面,所以这一步建议自定义安装,在进入到openoffice的安装program目录下,执行 soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard 这个命令就可以启动服务了。
2.SWFTools是一组用来处理Flash的swf文件的工具包,我们使用它将pdf文件转成swf文件! 下载地址:SWFTools官网下载 swftools-2013-04-09-1007.exe
3.FlexPaper是一个开源轻量级的在浏览器上显示各种文档的组件 下载地址:FlexPaper官网下载 版本1.5.1
4.JODConverter一个Java的OpenDocument 文件转换器,在此我们只用到它的jar包 下载地址:JODCConverter下载
2.开发过程
1.新建项目,将flexpaper文件中的js文件夹(包含了flexpaper_flash_debug.js,flexpaper_flash.js,jquery.js,这三个js文件主要是预览swf文件的插件)拷贝至网站根目录;将FlexPaperViewer.swf拷贝至网站根目录下(该文件主要是用在网页中播放swf文件的播放器),目录结构如下图:
注:需创建upload文件夹
2.创建fileUpload.jsp
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!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">
- <title>文档在线预览系统</title>
- <style>
- body {margin-top:100px;background:#fff;font-family: Verdana, Tahoma;}
- a {color:#CE4614;}
- #msg-box {color: #CE4614; font-size:0.9em;text-align:center;}
- #msg-box .logo {border-bottom:5px solid #ECE5D9;margin-bottom:20px;padding-bottom:10px;}
- #msg-box .title {font-size:1.4em;font-weight:bold;margin:0 0 30px 0;}
- #msg-box .nav {margin-top:20px;}
- </style>
- </head>
- <body>
- <div id="msg-box">
- <form name="form1" method="post" enctype="multipart/form-data" action="docUploadConvertAction.jsp">
- <div class="title">
- 请上传要处理的文件,过程可能需要几分钟,请稍候片刻。
- </div>
- <p>
- <input name="file1" type="file">
- </p>
- <p>
- <input type="submit" name="Submit" value="上传">
- </p>
- </form >
- </div>
- </body>
- </html>
3.创建转换页docUploadConvertAction.jsp
- <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
- <%@page import="java.io.*"%>
- <%@page import="java.util.Enumeration"%>
- <%@page import="com.oreilly.servlet.MultipartRequest"%>
- <%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
- <%@page import="com.cectsims.util.DocConverter"%>
- <%
- //文件上传采用cos组件上传,可更换为commons-fileupload上传,文件上传后,保存在upload文件夹
- //获取文件上传路径
- String saveDirectory =application.getRealPath("/")+"upload";
- //打印上传路径信息
- System.out.println(saveDirectory);
- //每个文件最大50m
- int maxPostSize = 50 * 1024 * 1024 ;
- //采用cos缺省的命名策略,重名后加1,2,3...如果不加dfp重名将覆盖
- DefaultFileRenamePolicy dfp = new DefaultFileRenamePolicy();
- //response的编码为"UTF-8",同时采用缺省的文件名冲突解决策略,实现上传,如果不加dfp重名将覆盖
- MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize,"UTF-8",dfp);
- //MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize,"UTF-8");
- //输出反馈信息
- Enumeration files = multi.getFileNames();
- while (files.hasMoreElements()) {
- System.err.println("ccc");
- String name = (String)files.nextElement();
- File f = multi.getFile(name);
- if(f!=null){
- String fileName = multi.getFilesystemName(name);
- //获取上传文件的扩展名
- String extName=fileName.substring(fileName.lastIndexOf(".")+1);
- //文件全路径
- String lastFileName= saveDirectory+"\\" + fileName;
- //获取需要转换的文件名,将路径名中的'\'替换为'/'
- String converfilename = saveDirectory.replaceAll("\\\\", "/")+"/"+fileName;
- System.out.println(converfilename);
- //调用转换类DocConverter,并将需要转换的文件传递给该类的构造方法
- DocConverter d = new DocConverter(converfilename);
- //调用conver方法开始转换,先执行doc2pdf()将office文件转换为pdf;再执行pdf2swf()将pdf转换为swf;
- d.conver();
- //调用getswfPath()方法,打印转换后的swf文件路径
- System.out.println(d.getswfPath());
- //生成swf相对路径,以便传递给flexpaper播放器
- String swfpath = "upload"+d.getswfPath().substring(d.getswfPath().lastIndexOf("/"));
- System.out.println(swfpath);
- //将相对路径放入sessio中保存
- session.setAttribute("swfpath", swfpath);
- out.println("上传的文件:"+lastFileName);
- out.println("文件类型"+extName);
- out.println("<hr>");
- }
- }
- %>
- <!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">
- <title>Insert title here</title>
- <style>
- body {margin-top:100px;background:#fff;font-family: Verdana, Tahoma;}
- a {color:#CE4614;}
- #msg-box {color: #CE4614; font-size:0.9em;text-align:center;}
- #msg-box .logo {border-bottom:5px solid #ECE5D9;margin-bottom:20px;padding-bottom:10px;}
- #msg-box .title {font-size:1.4em;font-weight:bold;margin:0 0 30px 0;}
- #msg-box .nav {margin-top:20px;}
- </style>
- </head>
- <body>
- <div>
- <form name="viewForm" id="form_swf" action="documentView.jsp" method="POST">
- <input type='submit' value='预览' class='BUTTON SUBMIT'/>
- </form>
- </div>
- </body>
- </html>
4.创建查看页documentView.jsp
- <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
- <%
- String swfFilePath=session.getAttribute("swfpath").toString();
- %>
- <!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="js/jquery.js"></script>
- <script type="text/javascript" src="js/flexpaper_flash.js"></script>
- <script type="text/javascript" src="js/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;">
- <a id="viewerPlaceHolder" style="width:820px;height:650px;display:block"></a>
- <script type="text/javascript">
- var fp = new FlexPaperViewer(
- 'FlexPaperViewer',
- 'viewerPlaceHolder', { config : {
- SwfFile : escape('<%=swfFilePath%>'),
- Scale : 0.6,
- ZoomTransition : 'easeOut',
- ZoomTime : 0.5,
- ZoomInterval : 0.2,
- FitPageOnLoad : true,
- FitWidthOnLoad : false,
- FullScreenAsMaxWindow : false,
- ProgressiveLoading : false,
- MinZoomSize : 0.2,
- MaxZoomSize : 5,
- SearchMatchAll : false,
- InitViewMode : 'SinglePage',
- ViewModeToolsVisible : true,
- ZoomToolsVisible : true,
- NavToolsVisible : true,
- CursorToolsVisible : true,
- SearchToolsVisible : true,
- localeChain: 'en_US'
- }});
- </script>
- </div>
- </body>
- </html>
5.创建转换类DocConverter.java
- package com.cectsims.util;
- import java.io.BufferedInputStream;
- import java.io.File;
- import java.io.IOException;
- import java.io.InputStream;
- 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);
- }
- /**
- * 重新设置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");
- 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("D:/Program Files/SWFTools/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) {
- 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");
- }
- }
- }
- }
3.参数说明
SwfFile (String) 需要使用Flexpaper打开的文档
Scale (Number) 初始化缩放比例,参数值应该是大于零的整数
ZoomTransition (String) Flexpaper中缩放样式,它使用和Tweener一样的样式,默认参数值为easeOut.其他可选值包括: easenone, easeout, linear, easeoutquad
ZoomTime (Number) 从一个缩放比例变为另外一个缩放比例需要花费的时间,该参数值应该为0或更大。
ZoomInterval (Number) 缩放比例之间间隔,默认值为0.1,该值为正数。
FitPageOnLoad (Boolean) 初始化得时候自适应页面,与使用工具栏上的适应页面按钮同样的效果。
FitWidthOnLoad (Boolean) 初始化的时候自适应页面宽度,与工具栏上的适应宽度按钮同样的效果。
localeChain (String) 设置地区(语言),目前支持以下语言。
en_US (English)
fr_FR (French)
zh_CN (Chinese, Simple)
es_ES (Spanish)
pt_BR (Brazilian Portugese)
ru_RU (Russian)
fi_FN (Finnish)
de_DE (German)
nl_NL (Netherlands)
tr_TR (Turkish)
se_SE (Swedish)
pt_PT (Portugese)
el_EL (Greek)
da_DN (Danish)
cz_CS (Czech)
it_IT (Italian)
pl_PL (Polish)
pv_FN (Finnish)
hu_HU (Hungarian)
FullScreenAsMaxWindow (Boolean) 当设置为true的时候,单击全屏按钮会打开一个flexpaper最大化的新窗口而不是全屏,当由于flash播放器因为安全而禁止全屏,而使用flexpaper作为独立的flash播放器的时候设置为true是个优先选择。
ProgressiveLoading (Boolean) 当设置为true的时候,展示文档时不会加载完整个文档,而是逐步加载,但是需要将文档转化为9以上的flash版本(使用pdf2swf的时候使用-T 9 标签)。
MaxZoomSize (Number) 设置最大的缩放比例。
MinZoomSize (Number) 最小的缩放比例。
SearchMatchAll (Boolean) 设置为true的时候,单击搜索所有符合条件的地方高亮显示。
InitViewMode (String) 设置启动模式如"Portrait" or "TwoPage".
ViewModeToolsVisible (Boolean) 工具栏上是否显示样式选择框。
ZoomToolsVisible (Boolean) 工具栏上是否显示缩放工具。
NavToolsVisible (Boolean) 工具栏上是否显示导航工具。
CursorToolsVisible (Boolean) 工具栏上是否显示光标工具。
SearchToolsVisible (Boolean) 工具栏上是否显示搜索。
对比本例子中的参数设置:
SwfFile : escape('FusionCharts.swf'),//加载的SWF文件为FusionCharts.swf
Scale : 0.6, //初始化缩放比例为0.6,即60%
ZoomTransition : 'easeOut',
ZoomTime : 0.5,
ZoomInterval : 0.2,
FitPageOnLoad : true,//加载时自动适应页面
FitWidthOnLoad : false, //加载时自动适应页面宽度
FullScreenAsMaxWindow : false,
ProgressiveLoading : false,
MinZoomSize : 0.2, //页面最小可缩小成20%
MaxZoomSize : 5, //页面最大可放大成500%
SearchMatchAll : false,
InitViewMode : 'Portrait',
PrintPaperAsBitmap : false,
ViewModeToolsVisible : true,
ZoomToolsVisible : true,
NavToolsVisible : true,
CursorToolsVisible : true,
SearchToolsVisible : true,
localeChain: 'en_US' //设置地区(语言)为en_US
上面带注解的参数为我们经常设置的参数,下面我们来简单演示一下几个参数改变的效果:
FitWidthOnLoad : false 改成true
MaxZoomSize : 5 改成1
localeChain: 'en_US'改成'zh_CN'
修改 flexpaper_flash.js文件中的width 和 height来改变预览页面的大小。