Java+FlexPaper+swfTools仿文库文档在线阅读

来源:互联网 发布:韩国电影断箭 知乎 编辑:程序博客网 时间:2024/05/02 02:38

原文出处:http://my.oschina.net/stephenzou/blog/144489?p=2

一、文档在线阅读思路 

    1.用OpenOffice把PPT、Word、Excel、Text转换为pdf
    2.用SWFTool将生成的pdf转换成swf,然后利用FlexPlayer实现在线预览播放
二、准备工作
    1.安装OpenOffice,官网下载地址:http://www.openoffice.org/download/index.html,最新版为3.4.1,我使用的版本为3.3.0:http://pan.baidu.com/share/link?shareid=1181746637&uk=1913152192#dir/path=%2F%E8%BD%AF%E4%BB%B6%E5%B7%A5%E5%85%B7
    2.启动OpenOffice服务,CMD命令进入OpenOffice安装目录下的program目录,键入如下命令
        soffice "-accept=socket,host=localhost,port=8100;urp;StarOffice.ServiceManager" -nologo -headless -nofirststartwizard
    
    参考资料:http://blog.csdn.net/hbcui1984/article/details/5109169
    3.下载JODConverter:http://sourceforge.net/projects/jodconverter/files/,项目中主要使用lib目录下的jar包。
    4.下载并安装SWFTools:http://www.swftools.org/download.html,下载exe文件安装完成即可
    5.下载FlexPlayer
    http://pan.baidu.com/share/link?shareid=1181746637&uk=1913152192#dir/path=%2F%E8%BD%AF%E4%BB%B6%E5%B7%A5%E5%85%B7
    官网下载地址:http://flexpaper.devaldi.com/download/,版本为2.1.5,与1.5.1有较大差别,未使用最新版。

三、软件开发 
    1.新建web项目并引入jar包
        阅读JODConverter/lib目录下的DEPENDENCIES.txt可知需要添加哪些jar包
        

        新建OfficeOnline项目,引入相应jar包(使用的是cos进行文档上传,cos.jar需要另外下载),将FlexPaper_1.5.1_flash.zip解压后的js目录引入到项目中,FlexPaperViewer.swf也引入进来
        
    2.新建DocConverter.java
        注意:根据SWFTools安装路径不同需要修改pdf2swf()方法中pdf2swf.exe的路径,我安装的路径是在D盘
                main()测试中根据自己文档路径进行修改测试。

001package com.util;
002 
003import java.io.BufferedReader;
004import java.io.File;
005import java.io.IOException;
006import java.io.InputStream;
007import java.io.InputStreamReader;
008 
009import com.artofsolving.jodconverter.DocumentConverter;
010import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
011import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
012import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
013 
014public class DocConverter {
015    private static final int environment = 1;// 环境1:windows,2:linux(涉及pdf2swf路径问题)
016    private String fileString;
017    private String outputPath = "";// 输入路径,如果不设置就输出在默认位置
018    private String fileName;
019    private File pdfFile;
020    private File swfFile;
021    private File docFile;
022 
023    public DocConverter(String fileString) {
024        ini(fileString);
025    }
026 
027    /*
028     * 重新设置 file @param fileString
029     */
030    public void setFile(String fileString) {
031        ini(fileString);
032    }
033 
034    /*
035     * 初始化 @param fileString
036     */
037    private void ini(String fileString) {
038        this.fileString = fileString;
039        fileName = fileString.substring(0, fileString.lastIndexOf("."));
040        docFile = new File(fileString);
041        pdfFile = new File(fileName + ".pdf");
042        swfFile = new File(fileName + ".swf");
043    }
044 
045    /*
046     * 转为PDF @param file
047     */
048    private void doc2pdf() throws Exception {
049        if (docFile.exists()) {
050            if (!pdfFile.exists()) {
051                OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
052                try {
053                    connection.connect();
054                    DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
055                    converter.convert(docFile, pdfFile);
056                    // close the connection
057                    connection.disconnect();
058                    System.out.println("****pdf转换成功,PDF输出:" + pdfFile.getPath() + "****");
059                } catch (java.net.ConnectException e) {
060                    // ToDo Auto-generated catch block
061                    e.printStackTrace();
062                    System.out.println("****swf转换异常,openoffice服务未启动!****");
063                    throw e;
064                } catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {
065                    e.printStackTrace();
066                    System.out.println("****swf转换器异常,读取转换文件失败****");
067                    throw e;
068                } catch (Exception e) {
069                    e.printStackTrace();
070                    throw e;
071                }
072            } else {
073                System.out.println("****已经转换为pdf,不需要再进行转化****");
074            }
075        } else {
076            System.out.println("****swf转换器异常,需要转换的文档不存在,无法转换****");
077        }
078    }
079 
080    /*
081     * 转换成swf
082     */
083    private void pdf2swf() throws Exception {
084        Runtime r = Runtime.getRuntime();
085        if (!swfFile.exists()) {
086            if (pdfFile.exists()) {
087                if (environment == 1)// windows环境处理
088                {
089                    try {
090                        // 这里根据SWFTools安装路径需要进行相应更改
091                        Process p = r.exec("d:/SWFTools/pdf2swf.exe " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9");
092                        System.out.print(loadStream(p.getInputStream()));
093                        System.err.print(loadStream(p.getErrorStream()));
094                        System.out.print(loadStream(p.getInputStream()));
095                        System.err.println("****swf转换成功,文件输出:" + swfFile.getPath() + "****");
096                        if (pdfFile.exists()) {
097                            pdfFile.delete();
098                        }
099                    } catch (Exception e) {
100                        e.printStackTrace();
101                        throw e;
102                    }
103                } else if (environment == 2)// linux环境处理
104                {
105                    try {
106                        Process p = r.exec("pdf2swf " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9");
107                        System.out.print(loadStream(p.getInputStream()));
108                        System.err.print(loadStream(p.getErrorStream()));
109                        System.err.println("****swf转换成功,文件输出:" + swfFile.getPath() + "****");
110                        if (pdfFile.exists()) {
111                            pdfFile.delete();
112                        }
113                    } catch (Exception e) {
114                        e.printStackTrace();
115                        throw e;
116                    }
117                }
118            } else {
119                System.out.println("****pdf不存在,无法转换****");
120            }
121        } else {
122            System.out.println("****swf已存在不需要转换****");
123        }
124    }
125 
126    static String loadStream(InputStream in) throws IOException {
127        int ptr = 0;
128        //把InputStream字节流 替换为BufferedReader字符流 2013-07-17修改
129        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
130        StringBuilder buffer = new StringBuilder();
131        while ((ptr = reader.read()) != -1) {
132            buffer.append((char) ptr);
133        }
134        return buffer.toString();
135    }
136 
137    /*
138     * 转换主方法
139     */
140    public boolean conver() {
141        if (swfFile.exists()) {
142            System.out.println("****swf转换器开始工作,该文件已经转换为swf****");
143            return true;
144        }
145 
146        if (environment == 1) {
147            System.out.println("****swf转换器开始工作,当前设置运行环境windows****");
148        } else {
149            System.out.println("****swf转换器开始工作,当前设置运行环境linux****");
150        }
151 
152        try {
153            doc2pdf();
154            pdf2swf();
155        } catch (Exception e) {
156            // TODO: Auto-generated catch block
157            e.printStackTrace();
158            return false;
159        }
160 
161        if (swfFile.exists()) {
162            return true;
163        } else {
164            return false;
165        }
166    }
167 
168    /*
169     * 返回文件路径 @param s
170     */
171    public String getswfPath() {
172        if (swfFile.exists()) {
173            String tempString = swfFile.getPath();
174            tempString = tempString.replaceAll("\\\\", "/");
175            return tempString;
176        } else {
177            return "";
178        }
179    }
180 
181    /*
182     * 设置输出路径
183     */
184    public void setOutputPath(String outputPath) {
185        this.outputPath = outputPath;
186        if (!outputPath.equals("")) {
187            String realName = fileName.substring(fileName.lastIndexOf("/"), fileName.lastIndexOf("."));
188            if (outputPath.charAt(outputPath.length()) == '/') {
189                swfFile = new File(outputPath + realName + ".swf");
190            else {
191                swfFile = new File(outputPath + realName + ".swf");
192            }
193        }
194    }
195 
196    public static void main(String s[]) {
197        DocConverter d = new DocConverter("E:/TDDOWNLOAD/test.doc");
198        d.conver();
199    }
200}

        运行结果: 
             
    3.新建 documentUpload.jsp 
    
01<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
02<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
03<html>
04    <head>
05        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
06        <title>文档在线预览系统</title>
07        <style>
08body {
09    margin-top: 100px;
10    background: #fff;
11    font-family: Verdana, Tahoma;
12}
13 
14a {
15    color: #CE4614;
16}
17 
18#msg-box {
19    color: #CE4614;
20    font-size: 0.9em;
21    text-align: center;
22}
23 
24#msg-box .logo {
25    border-bottom: 5px solid #ECE5D9;
26    margin-bottom: 20px;
27    padding-bottom: 10px;
28}
29 
30#msg-box .title {
31    font-size: 1.4em;
32    font-weight: bold;
33    margin: 0 0 30px 0;
34}
35 
36#msg-box .nav {
37    margin-top: 20px;
38}
39</style>
40    </head>
41    <body>
42        <div id="msg-box">
43            <form name="form1" method="post" enctype="multipart/form-data" action="docUploadConvertAction.jsp">
44                <div class="title">
45                    请上传要处理的文件,过程可能需要几分钟,请稍候片刻。
46                </div>
47                <p>
48                    <input name="file1" type="file">
49                </p>
50                <p>
51                    <input type="submit" name="Submit" value="上传">
52                </p>
53            </form>
54        </div>
55    </body>
56</html>
    4.新建docUploadConvertAction.jsp
        
01<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
02<%@page import="java.io.*"%>
03<%@page import="java.util.Enumeration"%>
04<%@page import="com.oreilly.servlet.MultipartRequest"%>
05<%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
06<%@page import="com.util.DocConverter"%>
07<%
08    //文件上传采用cos组件上传,可更换为commons-fileupload上传,文件上传后,保存在upload文件夹
09    //获取文件上传路径
10    String saveDirectory = application.getRealPath("/") + "upload";
11    //打印上传路径信息
12    System.out.println(saveDirectory);
13    //每个文件最大50m
14    int maxPostSize = 50 * 1024 * 1024;
15    //采用cos缺省的命名策略,重名后加1,2,3...如果不加dfp重名将覆盖
16    DefaultFileRenamePolicy dfp = new DefaultFileRenamePolicy();
17    //response的编码为"UTF-8",同时采用缺省的文件名冲突解决策略,实现上传,如果不加dfp重名将覆盖
18    MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize, "UTF-8", dfp);
19    //MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize,"UTF-8");
20    //输出反馈信息
21    Enumeration files = multi.getFileNames();
22    while (files.hasMoreElements()) {
23        System.err.println("ccc");
24        String name = (String) files.nextElement();
25        File f = multi.getFile(name);
26        if (f != null) {
27            String fileName = multi.getFilesystemName(name);
28            //获取上传文件的扩展名
29            String extName = fileName.substring(fileName.lastIndexOf(".") + 1);
30            //文件全路径
31            String lastFileName = saveDirectory + "\\" + fileName;
32            //获取需要转换的文件名,将路径名中的'\'替换为'/'
33            String converfilename = saveDirectory.replaceAll("\\\\", "/") + "/" + fileName;
34            System.out.println(converfilename);
35            //调用转换类DocConverter,并将需要转换的文件传递给该类的构造方法
36            DocConverter d = new DocConverter(converfilename);
37            //调用conver方法开始转换,先执行doc2pdf()将office文件转换为pdf;再执行pdf2swf()将pdf转换为swf;
38            d.conver();
39            //调用getswfPath()方法,打印转换后的swf文件路径
40            System.out.println(d.getswfPath());
41            //生成swf相对路径,以便传递给flexpaper播放器
42            String swfpath = "upload" + d.getswfPath().substring(d.getswfPath().lastIndexOf("/"));
43            System.out.println(swfpath);
44            //将相对路径放入sessio中保存
45            session.setAttribute("swfpath", swfpath);
46            out.println("上传的文件:" + lastFileName);
47            out.println("文件类型" + extName);
48            out.println("<hr>");
49        }
50    }
51%>
52<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
53<html>
54    <head>
55        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
56        <title>Insert title here</title>
57        <style>
58body {
59    margin-top: 100px;
60    background: #fff;
61    font-family: Verdana, Tahoma;
62}
63 
64a {
65    color: #CE4614;
66}
67 
68#msg-box {
69    color: #CE4614;
70    font-size: 0.9em;
71    text-align: center;
72}
73 
74#msg-box .logo {
75    border-bottom: 5px solid #ECE5D9;
76    margin-bottom: 20px;
77    padding-bottom: 10px;
78}
79 
80#msg-box .title {
81    font-size: 1.4em;
82    font-weight: bold;
83    margin: 0 0 30px 0;
84}
85 
86#msg-box .nav {
87    margin-top: 20px;
88}
89</style>
90    </head>
91    <body>
92        <div>
93            <form name="viewForm" id="form_swf" action="documentView.jsp" method="POST">
94                <input type='submit' value='预览' class='BUTTON SUBMIT' />
95            </form>
96        </div>
97    </body>
98</html>
    5.新建documentView.jsp
    
01<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
02<%
03    String swfFilePath = session.getAttribute("swfpath").toString();
04%>
05<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
06<html>
07    <head>
08        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
09        <script type="text/javascript" src="js/jquery.js"></script>
10        <script type="text/javascript" src="js/flexpaper_flash.js"></script>
11        <script type="text/javascript" src="js/flexpaper_flash_debug.js"></script>
12        <style type="text/css" media="screen">
13html,body {
14    height: 100%;
15}
16 
17body {
18    margin: 0;
19    padding: 0;
20    overflow: auto;
21}
22 
23#flashContent {
24    display: none;
25}
26</style>
27        <title>文档在线预览系统</title>
28    </head>
29    <body>
30        <div style="position: absolute; left: 50px; top: 10px;">
31            <a id="viewerPlaceHolder" style="width: 820px; height: 650px; display: block"></a>
32            <script type="text/javascript">
33                var fp = new FlexPaperViewer(  
34                         'FlexPaperViewer',
35                         'viewerPlaceHolder', { config : {
36                         SwfFile : escape('<%=swfFilePath%>'),//编码设置
37                         Scale : 0.6,
38                         ZoomTransition : 'easeOut',//变焦过渡
39                         ZoomTime : 0.5,
40                         ZoomInterval : 0.2,//缩放滑块-移动的缩放基础[工具栏]
41                         FitPageOnLoad : true,//自适应页面
42                         FitWidthOnLoad : true,//自适应宽度
43                         FullScreenAsMaxWindow : false,//全屏按钮-新页面全屏[工具栏]
44                         ProgressiveLoading : false,//分割加载
45                         MinZoomSize : 0.2,//最小缩放
46                         MaxZoomSize : 3,//最大缩放
47                         SearchMatchAll : true,
48                         InitViewMode : 'Portrait',//初始显示模式(SinglePage,TwoPage,Portrait)
49                          
50                         ViewModeToolsVisible : true,//显示模式工具栏是否显示
51                         ZoomToolsVisible : true,//缩放工具栏是否显示
52                         NavToolsVisible : true,//跳页工具栏
53                         CursorToolsVisible : false,
54                         SearchToolsVisible : true,
55                            PrintPaperAsBitmap:false,
56                         localeChain: 'en_US'
57                         }});
58            </script>
59        </div>
60    </body>
61</html>
        FlexPaperViewer参数设置对应说明文档:http://flexpaper.devaldi.com/docs_parameters.jsp
    6.部署后访问:http://localhost:8080/OfficeOnline/documentUpload.jsp
    
    上传成功后预览:
        
    7.若出现swf无法预览,请访问http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04a.html#119065将生成swf的文件夹设置为信任文件。
    8.参考资料:http://blog.csdn.net/hil2000/article/details/8459940
                        http://www.cnblogs.com/star-studio/archive/2011/12/09/2281807.html
                       文件中文名乱码解决:http://blog.csdn.net/kunoy/article/details/7903258

四、其他优化
    解决flexpaper搜索文字时不能高亮的问题: http://my.oschina.net/dianfusoft/blog/125450 
     flexpaper去简介去水印等:http://blog.csdn.net/zengraoli/article/details/7827840 
0 0
原创粉丝点击