在线预览文档

最近做了一个我的文库的项目,需要用到在线预览文档,上网查了很多资料,终于把它搞定,在此分享一下,我尽量会写的很详细,总体思路和网上的都差不多,就是一些细节,如果没有考虑到,效果就不会出来。

1,首先,我们需要安装一个openoffice ,这个资源我会上传上去,安装好之后要记住安装路径,因为要在windows的cmd命令下开启openoffice的服务,这个在每次重新启动windows的时候都要开启一遍,当然我这只是在windows上开发的,项目部署服务器上就不用这么麻烦了,先进入openoffice的安装目录下的/program目录下,直接输入命令:

soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard

这样我们就开启了openoffice的服务,

2,安装swfTools(安装到 D:\Program Files)swftools作用是将pdf转换为swf文件 这个工具我也会上传上去,这些工具的版本都是我实验过的,所以不会出现问题
以便flexpaper播放。下载地址:http://www.swftools.org/download.html   这个安装路径也要记着,java类中要调用本机安装的这个工具,具体看java那个转换类


3,
下载OpenDocument文档转换器 JODConverter,JODConverter是一个java的

OpenDucument文件转换器,可以进行许多文件格式的转换,它利用OpenOffice来进行

转换工作,它能进行以下的转换工作:
a.Microsoft Office格式转换为

OpenDucument,以及OpenDucument转换为Microsoft Office b.OpenDucument转换

为PDF,Word、Excel、PowerPoint转换为PDF,RTF转换为PDF等。 下载地址:

http://sourceforge.net/projects/jodconverter/files/ 我们后面开发主要用它

的jodconverter-2.2.2.jar包


4,下面我们就开始转换文档了,这里需要补充一下,我们在网页上看到预览的都是.swf格式的,普通的office文档或者txt格式的需要先转换为pdf格式,然后再转换为swf格式进行预览,那么我们就需要写一个java类,调用openoffice的服务来把文档转换为pdf格式的文件,这里我们先利用框架的上传功能上传要转换的文件,我这里用的是上structs的上传工具,相信接触过ssh框架的都会用,


这个是文档转成pdf的java类

package com.zy.library.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;

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 File/pdf2swf.exe "+ pdfFile.getPath() + " -o "+ swfFile.getPath() + " -T 9"); */ //这是网上写的命令,但是出不来效果,
                        Process p = r.exec("D:/Program File/pdf2swf.exe"+" -t "+ pdfFile.getPath() +" -s flashversion=9"+ " -o "+ swfFile.getPath());//这个是我修改过的,修改了版本问题,
                        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");  
            }  
        }  
    }  

 

}



这个是上传的页面
<%@ 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 #C5C1AA;
    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="up.action">

            <div class="title"> 请上传要处理的文件,过程可能需要几分钟,请稍候片刻。</div>

            <p>
                <input name="file1" type="file">
            </p>

            <p>
                <input type="submit" name="Submit" value="上传">
            </p>

        </form>

    </div>

</body>

</html>



这个是上传的action

package com.zy.library.hadoop.action;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.zy.library.core.action.BaseAction;
import com.zy.library.hadoop.mapreduce.collect.LibraryCollectThread;
import com.zy.library.hadoop.util.HadoopUtil;
import com.zy.library.util.Constants;
import com.zy.library.util.DocConverter;
import com.zy.library.util.PropUtil;

public class UploadAction extends BaseAction {

    private String libraryContentType;
    public File file1;
    public String file1FileName;
    private String path;
    public String upload() throws Exception{
        
        String filename = HadoopUtil.upload(file1,file1FileName);//返回的是上传文件的原文件名
        setMessage(getUploadJson(filename,file1FileName));
        
        String saveDirectory =ServletActionContext.getServletContext().getRealPath("/upload123");
        System.out.println(saveDirectory);
        String realFilePath=saveDirectory+"\\"+file1FileName;//文件全路径
        System.out.println(realFilePath);
        File file=new File(realFilePath);
        if(!file.getParentFile().exists()){
                File pFile=new File(saveDirectory);
        }
        FileUtils.copyFile(file1, file);
        String exename=file1FileName.substring(file1FileName.lastIndexOf(".")+1);//获取后缀名
        System.out.println(exename);
        //获取需要转换的文件名,将路径名中的'\'替换为'/'  
        String converFilePath=saveDirectory.replace("\\", "/")+"/"+file1FileName;
        System.out.println(converFilePath);
        //调用转换类DocConverter,并将需要转换的文件传递给该类的构造方法
        DocConverter d = new DocConverter(converFilePath);
        //调用conver方法开始转换,先执行doc2pdf()将office文件转换为pdf;再执行pdf2swf()将pdf转换为swf;  
        d.conver();
        file.delete();
        //调用getswfPath()方法,打印转换后的swf文件路径  
        System.out.println(d.getswfPath());
        String spath="/upload123/"+file1FileName.substring(0,file1FileName.lastIndexOf(".")+1)+"swf";
        setPath(spath);
        System.out.println("本地转换成功! 路径:"+path);
       
        return "success";
    }

    
    
    public File getFile1() {
        return file1;
    }



    public void setFile1(File file1) {
        this.file1 = file1;
    }



    public String getFile1FileName() {
        return file1FileName;
    }



    public void setFile1FileName(String file1FileName) {
        this.file1FileName = file1FileName;
    }



    public String getPath() {
        return path;
    }



    public void setPath(String path) {
        this.path = path;
    }


    public String getLibraryContentType() {
        return libraryContentType;
    }

    public void setLibraryContentType(String libraryContentType) {
        this.libraryContentType = libraryContentType;
    }
    
}


5,生成swf格式的文件后然后我们就可以用flexpaper预览了

下载flexpaper,下载地址:http://flexpaper.devaldi.com/download/

这个包我也上传了,可以直接拷到项目的WebContent下(我用的是eclipse),

示例展示jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- FlexPaperViewer flash version debug template -->
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>FlexPaper</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="../js/flexpaper_flash_debug.js"></script>
<script type="text/javascript" src="../js/jquery.js"></script>

</head>
<body>
    <div style="position: absolute; left: 10px; top: 10px;">
        <a id="viewerPlaceHolder"
            style="width: 680px; height: 480px; display: block"></a>

        <script type="text/javascript">
                var fp = new FlexPaperViewer(    
                         '../FlexPaperViewer',
                         'viewerPlaceHolder', { config : {
                         SwfFile :escape('/library123/upload123/jjjj.swf'),
                         Scale : 0.6,
                         ZoomTransition : 'easeOut',
                         ZoomTime : 0.5,
                         ZoomInterval : 0.2,
                         FitPageOnLoad : false,
                         FitWidthOnLoad : false,
                         FullScreenAsMaxWindow : false,
                         ProgressiveLoading : false,
                         MinZoomSize : 0.2,
                         MaxZoomSize : 5,
                         SearchMatchAll : false,
                         InitViewMode : 'Portrait',
                        
                         ViewModeToolsVisible : true,
                         ZoomToolsVisible : true,
                         NavToolsVisible : true,
                         CursorToolsVisible : true,
                         SearchToolsVisible : true,
                          
                           localeChain: 'en_US'
                         }});
            </script>
    </div>

</body>
</html>

用的时候只需要改变这个:SwfFile :escape('/library123/upload123/jjjj.swf')   里面的路径,library123是我的项目名,upload123是我设置的上传后的文件夹,这个是要展示的swf

其实这些小细节让我弄了好长时间,所以我特别要提一下。

我上传的文件中openoffice文件夹中的有两个exe文件,其中下面的那个是openoffice的中文语言包,最好也安装一下,因为有时候txt转pdf会出现中文乱码


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值