打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
FlexPaper+OpenOffice实现web的在线文档预览功能

一:准备工作

1.安装OpenOffice

2.下载FlexPaper

3.下载jodconverter

4.下载pinyin4j

5.下载swftools

二:相关代码

1.jsp页面

  1. <%@ page import="com.fjrj.util.FlashUtil" %>    
  2.   
  3. <%@ page contentType="text/html;charset=UTF-8" language="java" %>    
  4. <%    
  5.     String path = request.getContextPath();  
  6.   
  7.     //String filePath=request.getParameter("filePath");    
  8.     //String fileName=request.getParameter("fileName");  
  9.     String filePath = "path";    
  10.     String fileName="源文件.doc";  
  11.       
  12.     String applicationPath = application.getRealPath("");    
  13.     String targetPath=applicationPath+"\\tempSwfFile";    
  14.       
  15.     String flashFile = null;   
  16.     boolean flag = FlashUtil.copySourceFileToTarget(filePath, fileName, targetPath);    
  17.       
  18.     if(flag){  
  19.         flashFile = new FlashUtil().beginConvert(targetPath,fileName);//绝对路径   相对路径    
  20.     }  
  21.       
  22. %>    
  23. <html>    
  24. <head>    
  25.     <title>在线文档浏览</title>    
  26.     <style type="text/css" media="screen">    
  27.         html, body  { height:100%; }    
  28.         body { margin:0; padding:0; overflow:auto; }    
  29.     </style>    
  30.     <script type="text/javascript" src="<%=path%>/script/jquery-1.4.2.min.js"></script>  
  31.     <script type="text/javascript" src="<%=path%>/script/js/flexpaper_flash.js"></script>    
  32. </head>    
  33. <body>    
  34. <div style="position:absolute;left:0px;top:0px;width:100%;height:100%;">    
  35.     <a id="viewerPlaceHolder" style="width:100%;height:100%;display:block"></a>    
  36.     <script type="text/javascript">    
  37.         var fp = new FlexPaperViewer(    
  38.                 'FlexPaperViewer',    
  39.                 'viewerPlaceHolder', { config : {    
  40.                     SwfFile : escape('<%=path%>/tempSwfFile/<%=flashFile%>'),  //此处为项目中的地址  
  41.                     Scale : 0.6,    
  42.                     ZoomTransition : 'easeOut',    
  43.                     ZoomTime : 0.5,    
  44.                     ZoomInterval : 0.2,    
  45.                     FitPageOnLoad : true,    
  46.                     FitWidthOnLoad : false,    
  47.                     PrintEnabled : true,    
  48.                     FullScreenAsMaxWindow : false,    
  49.                     ProgressiveLoading : false,    
  50.                     MinZoomSize : 0.2,    
  51.                     MaxZoomSize : 5,    
  52.                     SearchMatchAll : false,    
  53.                     InitViewMode : 'Portrait',    
  54.     
  55.                     ViewModeToolsVisible : true,    
  56.                     ZoomToolsVisible : true,    
  57.                     NavToolsVisible : true,    
  58.                     CursorToolsVisible : true,    
  59.                     SearchToolsVisible : true,    
  60.     
  61.                     localeChain: 'zh_CN'    
  62.                 }});    
  63.     </script>    
  64.       
  65. </div>    
  66. </body>    
  67. </html>    
2.FlashUtil.java

  1. package com.fjrj.util;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.FileNotFoundException;  
  7. import java.io.FileOutputStream;  
  8. import java.io.IOException;  
  9. import java.io.InputStream;  
  10. import java.io.OutputStream;  
  11. import java.net.ConnectException;  
  12.   
  13. import com.artofsolving.jodconverter.DocumentConverter;  
  14. import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;  
  15. import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;  
  16. import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;  
  17.     
  18. /**  
  19.  */    
  20. public class FlashUtil {    
  21.     
  22.     public static  void main(String[] args){    
  23.         String outPath = new FlashUtil().beginConvert("","附件.pdf");    
  24.         System.out.println("生成swf文件:" + outPath);    
  25. //        boolean outPath = new FlashUtil().isExistFlash("123.pdf");    
  26. //        System.out.println("是否存在swf文件:" + outPath);    
  27.     }    
  28.     private static final String DOC = ".doc";    
  29.     private static final String DOCX = ".docx";    
  30.     private static final String XLS = ".xls";    
  31.     private static final String XLSX = ".xlsx";    
  32.     private static final String PDF = ".pdf";    
  33.     private static final String SWF = ".swf";    
  34.     private static final String TOOL = "pdf2swf.exe";    
  35.     
  36.     /**  
  37.      * 入口方法-通过此方法转换文件至swf格式  
  38.      * @param filePath 上传文件所在文件夹的绝对路径  
  39.      * @param fileName  文件名称  
  40.      * @return          生成swf文件名  
  41.      */    
  42.     public String beginConvert(String filePath,String fileName) {    
  43.         String outFile = "";    
  44.         String fileNameOnly = "";    
  45.         String fileExt = "";    
  46.         if (null != fileName && fileName.indexOf(".") > 0) {    
  47.             int index = fileName.indexOf(".");    
  48.             fileNameOnly = fileName.substring(0, index);    
  49.             fileExt = fileName.substring(index).toLowerCase();    
  50.         }    
  51.         String inputFile = filePath + File.separator + fileName;    
  52.         String outputFile = "";    
  53.         //如果是flash文件,直接显示    
  54.         if(fileExt.equals(SWF)){    
  55.             outFile = fileName;    
  56.         }else {    
  57.             //主要是针对中文汉字转拼音    
  58.             fileNameOnly = new CnToSpell().getPinYin(fileNameOnly);    
  59.             //如果存在对应的flash文件    
  60.             boolean  isExistFlash = isExistFlash(filePath,fileNameOnly);    
  61.             if(isExistFlash){    
  62.                 outFile = fileNameOnly + SWF;    
  63.             }else {    
  64.                 //如果是office文档,先转为pdf文件    
  65.                 if (fileExt.equals(DOC) || fileExt.equals(DOCX) || fileExt.equals(XLS)    
  66.                         || fileExt.equals(XLSX)) {    
  67.                     outputFile = filePath + File.separator + fileNameOnly + PDF;    
  68.                     File pdfFile = new File(outputFile);    
  69.                     if(!pdfFile.exists()){//判断pdf文件是否已经生成    
  70.                         office2PDF(inputFile, outputFile);    
  71.                     }    
  72.                     inputFile = outputFile;    
  73.                     fileExt = PDF;    
  74.                 }    
  75.                 if (fileExt.equals(PDF)) {    
  76.                     outputFile = filePath + File.separator + fileNameOnly + SWF;    
  77.                     outputFile = outputFile.replace("\\","/");    
  78.                     File swfFile = new File(outputFile);    
  79.                     if(!swfFile.exists()){//判断swf文件是否已经生成    
  80.                         File parentFolder = swfFile.getParentFile();    
  81.                         if(parentFolder!=null&&!parentFolder.exists()){    
  82.                             parentFolder.mkdirs();    
  83.                         }    
  84.                         String toolFile = null;    
  85.                         if(filePath.indexOf("flexpaper")==-1){    
  86.                             toolFile = filePath + File.separator +"flexpaper"+ File.separator + TOOL;    
  87.                         }else{    
  88.                             toolFile = filePath + File.separator + TOOL;    
  89.                         }    
  90.                         convertPdf2Swf(inputFile, outputFile, toolFile);    
  91.                     }    
  92.                     outFile = fileNameOnly + SWF;    
  93.                 }    
  94.             }    
  95.         }    
  96.         return outFile;    
  97.     }    
  98.     
  99.     /**  
  100.      * 将pdf文件转换成swf文件  
  101.      * @param sourceFile pdf文件绝对路径  
  102.      * @param outFile    swf文件绝对路径  
  103.      * @param toolFile   转换工具绝对路径  
  104.      */    
  105.     private void convertPdf2Swf(String sourceFile, String outFile,    
  106.                                 String toolFile) {    
  107.         String command = toolFile + " \"" + sourceFile + "\" -o  \"" + outFile    
  108.                 + "\" -s flashversion=9 ";    
  109.         try {    
  110.             Process process = Runtime.getRuntime().exec(command);    
  111.             System.out.println(loadStream(process.getInputStream()));    
  112.             System.err.println(loadStream(process.getErrorStream()));    
  113.             System.out.println(loadStream(process.getInputStream()));    
  114.             System.out.println("###--Msg: swf 转换成功");    
  115.         } catch (Exception e) {    
  116.             e.printStackTrace();    
  117.         }    
  118.     }    
  119.     
  120.     /**  
  121.      * 检测文件夹下是否已存在对应的flash文件  
  122.      * @return  
  123.      */    
  124.         private boolean isExistFlash(String filePath,String fileNameOnly){    
  125.             String fileName = fileNameOnly.substring(fileNameOnly.lastIndexOf("/")+1);    
  126.             String newFilePath = fileNameOnly.substring(0 ,fileNameOnly.lastIndexOf("/")+1);    
  127.             File file = new File(filePath + File.separator+newFilePath);    
  128.             if(!file.exists()){//判断是否已经生成新文件夹,然后再去判断文件夹是否存在对应的flash文件    
  129.                 return false;    
  130.             }    
  131.             File[] files = file.listFiles();    
  132.             for(int j=0;j<files.length;j++){    
  133.                 if(files[j].isFile()){    
  134.                     String filesName = files[j].getName();    
  135.                     if(filesName.indexOf(".")!=-1){    
  136.                         if(SWF.equals(filesName.substring(filesName.lastIndexOf(".")).toLowerCase())){    
  137.                                 if(fileName.equals(filesName.substring(0,filesName.lastIndexOf(".")))){    
  138.                                     return true;    
  139.                                 }    
  140.                         }    
  141.                     }    
  142.                 }    
  143.             }    
  144.             return false;    
  145.         }    
  146.     
  147.     /**  
  148.      * office文档转pdf文件  
  149.      * @param sourceFile    office文档绝对路径  
  150.      * @param destFile      pdf文件绝对路径  
  151.      * @return  
  152.      */    
  153.     private int office2PDF(String sourceFile, String destFile) {    
  154.         //OpenOfficeProperty porperty = (OpenOfficeProperty)BeanUtil.getBean(req,"OpenOfficeProperty");  
  155.         String OpenOffice_HOME = "C:\\Program Files (x86)\\OpenOffice 4";    
  156.         String host_Str = "127.0.0.1";    
  157.         String port_Str = "8100";    
  158.         try {    
  159.             File inputFile = new File(sourceFile);    
  160.             if (!inputFile.exists()) {    
  161.                 return -1; // 找不到源文件    
  162.             }    
  163.             // 如果目标路径不存在, 则新建该路径    
  164.             File outputFile = new File(destFile);    
  165.             if (!outputFile.getParentFile().exists()) {    
  166.                 outputFile.getParentFile().mkdirs();    
  167.             }    
  168.             // 启动OpenOffice的服务    
  169.             String command = OpenOffice_HOME    
  170.                     + "\\program\\soffice.exe -headless -accept=\"socket,host="    
  171.                     + host_Str + ",port=" + port_Str + ";urp;\"";    
  172.             System.out.println("###\n" + command);    
  173.             Process pro = Runtime.getRuntime().exec(command);    
  174.             // 连接openoffice服务    
  175.             OpenOfficeConnection connection = new SocketOpenOfficeConnection(    
  176.                     host_Str, Integer.parseInt(port_Str));    
  177.             connection.connect();    
  178.             // 转换    
  179.             DocumentConverter converter = new OpenOfficeDocumentConverter(    
  180.                     connection);    
  181.             converter.convert(inputFile, outputFile);    
  182.     
  183.             // 关闭连接和服务    
  184.             connection.disconnect();    
  185.             pro.destroy();    
  186.     
  187.             return 0;    
  188.         } catch (FileNotFoundException e) {    
  189.             System.out.println("文件未找到!");    
  190.             e.printStackTrace();    
  191.             return -1;    
  192.         } catch (ConnectException e) {    
  193.             System.out.println("OpenOffice服务监听异常!");    
  194.             e.printStackTrace();    
  195.         } catch (IOException e) {    
  196.             e.printStackTrace();    
  197.         }    
  198.         return 1;    
  199.     }    
  200.     
  201.     static String loadStream(InputStream in) throws IOException{    
  202.         int ptr = 0;    
  203.         in = new BufferedInputStream(in);    
  204.         StringBuffer buffer = new StringBuffer();    
  205.     
  206.         while ((ptr=in.read())!= -1){    
  207.             buffer.append((char)ptr);    
  208.         }    
  209.         return buffer.toString();    
  210.     }    
  211.       
  212.     public static boolean copySourceFileToTarget(String sourcePath,String sourceName,String TargetPath){  
  213.         String srcFileName=sourcePath+File.separator+sourceName;  
  214.         String destFileName=TargetPath+File.separator+sourceName;  
  215.         return copyFile(srcFileName, destFileName, false);  
  216.     }  
  217.       
  218.     /**  
  219.      * 复制单个文件  
  220.      *   
  221.      * @param srcFileName  
  222.      *            待复制的文件名  
  223.      * @param descFileName  
  224.      *            目标文件名  
  225.      * @param overlay  
  226.      *            如果目标文件存在,是否覆盖  
  227.      * @return 如果复制成功返回true,否则返回false  
  228.      */    
  229.     public static boolean copyFile(String srcFileName, String destFileName,    
  230.             boolean overlay) {    
  231.         File srcFile = new File(srcFileName);    
  232.         // 判断源文件是否存在    
  233.         if (!srcFile.exists()) {    
  234.             System.out.println("源文件:" + srcFileName + "不存在!");     
  235.             return false;    
  236.         } else if (!srcFile.isFile()) {    
  237.             System.out.println("复制文件失败,源文件:" + srcFileName + "不是一个文件!");    
  238.             return false;    
  239.         }    
  240.         // 判断目标文件是否存在    
  241.         File destFile = new File(destFileName);    
  242.         if (destFile.exists()) {    
  243.             // 如果目标文件存在并允许覆盖    
  244.             if (overlay) {    
  245.                 // 删除已经存在的目标文件,无论目标文件是目录还是单个文件    
  246.                 new File(destFileName).delete();    
  247.             }else {  
  248.                 System.out.println("复制文件失败,目标文件"+destFileName+"已经存在");  
  249.                 return true;  
  250.             }    
  251.         } else {    
  252.             // 如果目标文件所在目录不存在,则创建目录    
  253.             if (!destFile.getParentFile().exists()) {    
  254.                 // 目标文件所在目录不存在    
  255.                 if (!destFile.getParentFile().mkdirs()) {    
  256.                     // 复制文件失败:创建目标文件所在目录失败    
  257.                     return false;    
  258.                 }    
  259.             }    
  260.         }    
  261.         // 复制文件    
  262.         int byteread = 0; // 读取的字节数    
  263.         InputStream in = null;    
  264.         OutputStream out = null;    
  265.     
  266.         try {    
  267.             in = new FileInputStream(srcFile);    
  268.             out = new FileOutputStream(destFile);    
  269.             byte[] buffer = new byte[1024];    
  270.     
  271.             while ((byteread = in.read(buffer)) != -1) {    
  272.                 out.write(buffer, 0, byteread);    
  273.             }    
  274.             return true;    
  275.         } catch (FileNotFoundException e) {    
  276.             return false;    
  277.         } catch (IOException e) {    
  278.             return false;    
  279.         } finally {    
  280.             try {    
  281.                 if (out != null)    
  282.                     out.close();    
  283.                 if (in != null)    
  284.                     in.close();    
  285.             } catch (IOException e) {    
  286.                 e.printStackTrace();    
  287.             }    
  288.         }    
  289.     }   
  290.       
  291. }    
3.CnToSpell.java

  1. package com.fjrj.util;  
  2.   
  3. import net.sourceforge.pinyin4j.PinyinHelper;    
  4. import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;    
  5. import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;    
  6. import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;    
  7. import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;    
  8. import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;    
  9.     
  10. /**  
  11.  */    
  12. public class CnToSpell {    
  13.     
  14.     public  String getPinYin(String src) {    
  15.         char[] t1 = null;    
  16.         t1 = src.toCharArray();    
  17.         String[] t2 = new String[t1.length];    
  18.         // 设置汉字拼音输出的格式    
  19.         HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();    
  20.         t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);    
  21.         t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);    
  22.         t3.setVCharType(HanyuPinyinVCharType.WITH_V);    
  23.         String t4 = "";    
  24.         int t0 = t1.length;    
  25.         try {    
  26.             for (int i = 0; i < t0; i++) {    
  27.                 // 判断是否为汉字字符    
  28.                 if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {    
  29.                     t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);// 将汉字的几种全拼都存到t2数组中    
  30.                     t4 += t2[0];// 取出该汉字全拼的第一种读音并连接到字符串t4后    
  31.                 } else {    
  32.                     // 如果不是汉字字符,直接取出字符并连接到字符串t4后    
  33.                     t4 += Character.toString(t1[i]);    
  34.                 }    
  35.             }    
  36.         } catch (BadHanyuPinyinOutputFormatCombination e) {    
  37.             e.printStackTrace();    
  38.         }    
  39.         if(t4.indexOf("【")!=-1){    
  40.             t4 = t4.replace("【","[");    
  41.         }    
  42.         if(t4.indexOf("】")!=-1){    
  43.             t4 = t4.replace("】","]");    
  44.         }    
  45.         if(t4.indexOf("(")!=-1){    
  46.             t4 = t4.replace("(","(");    
  47.         }    
  48.         if(t4.indexOf(")")!=-1){    
  49.             t4 = t4.replace(")",")");    
  50.         }    
  51.         return t4;    
  52.     }    
  53.     
  54.     
  55.     public  String getPinYinHeadChar(String str) {    
  56.         String convert = "";    
  57.         for (int j = 0; j < str.length(); j++) {    
  58.             char word = str.charAt(j);    
  59.             // 提取汉字的首字母    
  60.             String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);    
  61.             if (pinyinArray != null) {    
  62.                 convert += pinyinArray[0].charAt(0);    
  63.             } else {    
  64.                 convert += word;    
  65.             }    
  66.         }    
  67.         return convert;    
  68.     }    
  69.     
  70.     
  71.     public  String getCnASCII(String cnStr) {    
  72.         StringBuffer strBuf = new StringBuffer();    
  73.         // 将字符串转换成字节序列    
  74.         byte[] bGBK = cnStr.getBytes();    
  75.         for (int i = 0; i < bGBK.length; i++) {    
  76.             strBuf.append(Integer.toHexString(bGBK[i] & 0xff));    
  77.         }    
  78.         return strBuf.toString();    
  79.     }    
  80.     
  81.     public static void main(String[] args) {    
  82.         CnToSpell cnToSpell = new CnToSpell();    
  83.         String cnStr = "中华人民共和国(A-C)(12)_12345";    
  84.         System.out.println(cnToSpell.getPinYin(cnStr));    
  85.         System.out.println(cnToSpell.getPinYinHeadChar(cnStr));    
  86.         System.out.println(cnToSpell.getCnASCII(cnStr));    
  87.     }    
  88. }    


实现:在不改变原先的功能基础上,增加预览功能。


效果图:



注:

1.可将启动openoffice的服务配置置于配置文件中,方便修改

2.FlexPaperViewer.swf文件要置于当前的jsp页面目录下

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
swftools转换文件时线程堵塞问题的解决方法
Java+FlexPaper+swfTools仿百度文库文档在线预览系统设计与实现
实现一个具有百度文库文档转换功能的工具类
网页文档在线浏览(仿百度文库设计)
java多个文件合并为一个文件
jsp文件下载完整方法
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服