`
Dxx23
  • 浏览: 140965 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

FlexPaper+SWFTools ,java实现在线文档浏览

阅读更多
1、安装openoffice,OpenOffice_3.4.0_Win_x86_zh-CN.zip,使用新建OpenOfficeService.properties文件,放到src目录下
OO_HOME = C:\\Program Files (x86)\\OpenOffice.org 3
oo_host = 127.0.0.1
oo_port = 8100


2、下载 jodconverter-2.2.2,将lib目录所有jar 复制到项目 lib目录

3、 下载swftools-0.9.2.exe 安装后,复制安装目录中到 pdf2swf.exe 到项目附件目录中。

4、下载Flexpaper,引用其中的js

5、在环境变量中的Path配置如下:(注最后的“;”不要)
C:\Program Files (x86)\OpenOffice.org 3\program;D:\IdeaProjects\zsbk\zsbk\out\artifacts\zsbk_war_exploded\JS\StreetMap\flexpaper

<%@ page import="com.xxx.util.FlashUtil" %>
<%--
  Created by IntelliJ IDEA.
  Date: 13-7-11
  Time: 上午8:34
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String applicationPath = application.getRealPath("");
//    String filePath="http://x.x.x.x/JieJing/";
    String fileName=request.getParameter("fileName");
    String contextPath = request.getContextPath();
    String flashFile = null;
    String filePath = null;
    if(fileName.indexOf("gisPhotos")!=-1){
        fileName = fileName.substring(fileName.lastIndexOf("gisPhotos/"),fileName.length());
        filePath =applicationPath + "\\JS\\StreetMap";
        flashFile = new FlashUtil().beginConvert(filePath,fileName);//绝对路径   相对路径
        flashFile = "\\JS\\StreetMap\\" +flashFile;
        flashFile = contextPath+flashFile.replace("\\","/");
    }else{
        filePath =applicationPath + "\\JS\\StreetMap\\flexpaper";
//    fileName = new String(fileName.getBytes("ISO-8859-1"),"UTF-8");
        flashFile = new FlashUtil().beginConvert(filePath,fileName);//绝对路径   相对路径
    }
%>
<html>
<head>
    <title>在线文档浏览</title>
    <style type="text/css" media="screen">
        html, body	{ height:100%; }
        body { margin:0; padding:0; overflow:auto; }
    </style>

    <script type="text/javascript" src="js/flexpaper_flash.js"></script>
</head>
<body>
<div style="position:absolute;left:0px;top:0px;width:100%;height:100%;">
    <a id="viewerPlaceHolder" style="width:100%;height:100%;display:block"></a>

    <script type="text/javascript">
        var fp = new FlexPaperViewer(
                'FlexPaperViewer',
                'viewerPlaceHolder', { config : {
                    SwfFile : escape('<%=flashFile%>'),
                    Scale : 0.6,
                    ZoomTransition : 'easeOut',
                    ZoomTime : 0.5,
                    ZoomInterval : 0.2,
                    FitPageOnLoad : true,
                    FitWidthOnLoad : false,
                    PrintEnabled : true,
                    FullScreenAsMaxWindow : false,
                    ProgressiveLoading : false,
                    MinZoomSize : 0.2,
                    MaxZoomSize : 5,
                    SearchMatchAll : false,
                    InitViewMode : 'Portrait',

                    ViewModeToolsVisible : true,
                    ZoomToolsVisible : true,
                    NavToolsVisible : true,
                    CursorToolsVisible : true,
                    SearchToolsVisible : true,

                    localeChain: 'zh_CN'
                }});
    </script>
</div>
</body>
</html>


package com.xxx.util;


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;

/**
 * Created with IntelliJ IDEA.
 * Date: 13-7-11
 * Time: 上午10:46
 * To change this template use File | Settings | File Templates.
 */
public class FlashUtil {

    public static  void main(String[] args){
        String outPath = new FlashUtil().beginConvert("","附件.pdf");
        System.out.println("生成swf文件:" + outPath);
//        boolean outPath = new FlashUtil().isExistFlash("123.pdf");
//        System.out.println("是否存在swf文件:" + outPath);
    }
    private static final String DOC = ".doc";
    private static final String DOCX = ".docx";
    private static final String XLS = ".xls";
    private static final String XLSX = ".xlsx";
    private static final String PDF = ".pdf";
    private static final String SWF = ".swf";
    private static final String TOOL = "pdf2swf.exe";

    /**
     * 入口方法-通过此方法转换文件至swf格式
     * @param filePath 上传文件所在文件夹的绝对路径
     * @param fileName	文件名称
     * @return			生成swf文件名
     */
    public String beginConvert(String filePath,String fileName) {
        String outFile = "";
        String fileNameOnly = "";
        String fileExt = "";
        if (null != fileName && fileName.indexOf(".") > 0) {
            int index = fileName.indexOf(".");
            fileNameOnly = fileName.substring(0, index);
            fileExt = fileName.substring(index).toLowerCase();
        }
        String inputFile = filePath + File.separator + fileName;
        String outputFile = "";
        //如果是flash文件,直接显示
        if(fileExt.equals(SWF)){
            outFile = fileName;
        }else {
            //主要是针对中文汉字转拼音
            fileNameOnly = new CnToSpell().getPinYin(fileNameOnly);
            //如果存在对应的flash文件
            boolean  isExistFlash = isExistFlash(filePath,fileNameOnly);
            if(isExistFlash){
                outFile = fileNameOnly + SWF;
            }else {
                //如果是office文档,先转为pdf文件
                if (fileExt.equals(DOC) || fileExt.equals(DOCX) || fileExt.equals(XLS)
                        || fileExt.equals(XLSX)) {
                    outputFile = filePath + File.separator + fileNameOnly + PDF;
                    File pdfFile = new File(outputFile);
                    if(!pdfFile.exists()){//判断pdf文件是否已经生成
                        office2PDF(inputFile, outputFile);
                    }
                    inputFile = outputFile;
                    fileExt = PDF;
                }
                if (fileExt.equals(PDF)) {
                    outputFile = filePath + File.separator + fileNameOnly + SWF;
                    outputFile = outputFile.replace("\\","/");
                    File swfFile = new File(outputFile);
                    if(!swfFile.exists()){//判断swf文件是否已经生成
                        File parentFolder = swfFile.getParentFile();
                        if(parentFolder!=null&&!parentFolder.exists()){
                            parentFolder.mkdirs();
                        }
                        String toolFile = null;
                        if(filePath.indexOf("flexpaper")==-1){
                            toolFile = filePath + File.separator +"flexpaper"+ File.separator + TOOL;
                        }else{
                            toolFile = filePath + File.separator + TOOL;
                        }
                        convertPdf2Swf(inputFile, outputFile, toolFile);
                    }
                    outFile = fileNameOnly + SWF;
                }
            }
        }
        return outFile;
    }

    /**
     * 将pdf文件转换成swf文件
     * @param sourceFile pdf文件绝对路径
     * @param outFile	 swf文件绝对路径
     * @param toolFile	 转换工具绝对路径
     */
    private void convertPdf2Swf(String sourceFile, String outFile,
                                String toolFile) {
        String command = toolFile + " \"" + sourceFile + "\" -o  \"" + outFile
                + "\" -s flashversion=9 ";
        try {
            Process process = Runtime.getRuntime().exec(command);
            System.out.println(loadStream(process.getInputStream()));
            System.err.println(loadStream(process.getErrorStream()));
            System.out.println(loadStream(process.getInputStream()));
            System.out.println("###--Msg: swf 转换成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检测文件夹下是否已存在对应的flash文件
     * @return
     */
        private boolean isExistFlash(String filePath,String fileNameOnly){
            String fileName = fileNameOnly.substring(fileNameOnly.lastIndexOf("/")+1);
            String newFilePath = fileNameOnly.substring(0 ,fileNameOnly.lastIndexOf("/")+1);
            File file = new File(filePath + File.separator+newFilePath);
            if(!file.exists()){//判断是否已经生成新文件夹,然后再去判断文件夹是否存在对应的flash文件
                return false;
            }
            File[] files = file.listFiles();
            for(int j=0;j<files.length;j++){
                if(files[j].isFile()){
                    String filesName = files[j].getName();
                    if(filesName.indexOf(".")!=-1){
                        if(SWF.equals(filesName.substring(filesName.lastIndexOf(".")).toLowerCase())){
                                if(fileName.equals(filesName.substring(0,filesName.lastIndexOf(".")))){
                                    return true;
                                }
                        }
                    }
                }
            }
            return false;
        }

    /**
     * office文档转pdf文件
     * @param sourceFile	office文档绝对路径
     * @param destFile		pdf文件绝对路径
     * @return
     */
    private int office2PDF(String sourceFile, String destFile) {
        String OpenOffice_HOME = CommUtil.OpenOffice_HOME;
        String host_Str = CommUtil.host_Str;
        String port_Str = CommUtil.port_Str;
        try {
            File inputFile = new File(sourceFile);
            if (!inputFile.exists()) {
                return -1; // 找不到源文件
            }
            // 如果目标路径不存在, 则新建该路径
            File outputFile = new File(destFile);
            if (!outputFile.getParentFile().exists()) {
                outputFile.getParentFile().mkdirs();
            }
            // 启动OpenOffice的服务
            String command = OpenOffice_HOME
                    + "\\program\\soffice.exe -headless -accept=\"socket,host="
                    + host_Str + ",port=" + port_Str + ";urp;\"";
            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(inputFile, outputFile);

            // 关闭连接和服务
            connection.disconnect();
            pro.destroy();

            return 0;
        } catch (FileNotFoundException e) {
            System.out.println("文件未找到!");
            e.printStackTrace();
            return -1;
        } catch (ConnectException e) {
            System.out.println("OpenOffice服务监听异常!");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 1;
    }

    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();
    }
}




package xxx.platform.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * Created with IntelliJ IDEA.
 * User: xxx
 * Date: 13-7-12
 * Time: 下午3:52
 * To change this template use File | Settings | File Templates.
 */
public class CnToSpell {

    public  String getPinYin(String src) {
        char[] t1 = null;
        t1 = src.toCharArray();
        String[] t2 = new String[t1.length];
        // 设置汉字拼音输出的格式
        HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
        t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        t3.setVCharType(HanyuPinyinVCharType.WITH_V);
        String t4 = "";
        int t0 = t1.length;
        try {
            for (int i = 0; i < t0; i++) {
                // 判断是否为汉字字符
                if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {
                    t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);// 将汉字的几种全拼都存到t2数组中
                    t4 += t2[0];// 取出该汉字全拼的第一种读音并连接到字符串t4后
                } else {
                    // 如果不是汉字字符,直接取出字符并连接到字符串t4后
                    t4 += Character.toString(t1[i]);
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }
        if(t4.indexOf("【")!=-1){
            t4 = t4.replace("【","[");
        }
        if(t4.indexOf("】")!=-1){
            t4 = t4.replace("】","]");
        }
        if(t4.indexOf("(")!=-1){
            t4 = t4.replace("(","(");
        }
        if(t4.indexOf(")")!=-1){
            t4 = t4.replace(")",")");
        }
        return t4;
    }


    public  String getPinYinHeadChar(String str) {
        String convert = "";
        for (int j = 0; j < str.length(); j++) {
            char word = str.charAt(j);
            // 提取汉字的首字母
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert += pinyinArray[0].charAt(0);
            } else {
                convert += word;
            }
        }
        return convert;
    }


    public  String getCnASCII(String cnStr) {
        StringBuffer strBuf = new StringBuffer();
        // 将字符串转换成字节序列
        byte[] bGBK = cnStr.getBytes();
        for (int i = 0; i < bGBK.length; i++) {
            strBuf.append(Integer.toHexString(bGBK[i] & 0xff));
        }
        return strBuf.toString();
    }

    public static void main(String[] args) {
        CnToSpell cnToSpell = new CnToSpell();
        String cnStr = "中华人民共和国(A-C)(12)_12345";
        System.out.println(cnToSpell.getPinYin(cnStr));
        System.out.println(cnToSpell.getPinYinHeadChar(cnStr));
        System.out.println(cnToSpell.getCnASCII(cnStr));
    }
}


package xxx.platform.util;

import java.util.ResourceBundle;

/**
 * Created with IntelliJ IDEA.
 * User: xxx
 * Date: 13-7-12
 * Time: 上午8:42
 * To change this template use File | Settings | File Templates.
 */
public class CommUtil {
    public static final String OpenOffice_HOME;
    public static final String host_Str;
    public static final String port_Str;

    static {
        ResourceBundle rb = ResourceBundle.getBundle("OpenOfficeService");
        OpenOffice_HOME = rb.getString("OO_HOME");
        host_Str = rb.getString("oo_host");
        port_Str = rb.getString("oo_port");
    }

    public static int strToInt(String str){
        int i =0;
        if(str!=null&&!"".equals(str)){
            i = Integer.parseInt(str);
        }
        return i;
    }
    public static double strToDouble(String str){
        double d =0.0;
        if(str!=null&&!"".equals(str)){
            d = Double.parseDouble(str);
        }
        return d;
    }
}


参考:
http://blog.csdn.net/authorzhh/article/details/7470048

http://www.cnblogs.com/qinpeifeng107/archive/2011/08/29/2158879.html
分享到:
评论
3 楼 shayuan312 2015-11-24  
楼主您好,可以把这个的源码给我发一份么?395428137@qq.com 你这个我看了好久没实现啊 拜托大神了
2 楼 Dxx23 2014-02-25  
zengxuefei 写道
,贴出来的代码根本不能执行,好多错误,尤其是缺少了CnToSpell和CommUtil类。楼主说的步骤走确定已经完成没有错误

已补充两个公共类,其他架包什么的自己下,是一个成功事例,所以才把代码贴上。
1 楼 zengxuefei 2014-02-21  
,贴出来的代码根本不能执行,好多错误,尤其是缺少了CnToSpell和CommUtil类。楼主说的步骤走确定已经完成没有错误

相关推荐

Global site tag (gtag.js) - Google Analytics