码迷,mamicode.com
首页 > 其他好文 > 详细

模仿百度文库

时间:2014-05-07 19:06:44      阅读:591      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   class   code   java   

---恢复内容开始---

方案:

Txt/Word/Excel/PPT=>PDF(OpenOffice+JodConverter)=>SWF(pdf2swf)=>FlexPaper浏览

第一步:

Txt/Word/Excel/PPT=>PDF(OpenOffice+JodConverter)

准备:

1.下载:Apache_OpenOffice_incubating_3.4.1_Win_x86_install_zh-CN.exe

下载地址http://www.openoffice.org/download/index.html

2:所需jar包:

bubuko.com,布布扣bubuko.com,布布扣

 

3:源文件

bubuko.com,布布扣
package com.wyh.toPdf;

import java.io.File;
import java.util.Date;
import java.util.regex.Pattern;

import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;

/**
 * 这是一个工具类,主要是为了使Office全部格式的文档转化为pdf文件
 *
 */
public class Office2PDF {

    /**
     * office中.doc格式
     */
    public static final String OFFICE_DOC = "doc";
    /**
     * office中.docx格式
     */
    public static final String OFFICE_DOCX = "docx";
    /**
     * office中.xls格式
     */
    public static final String OFFICE_XLS = "xls";
    /**
     * office中.xlsx格式
     */
    public static final String OFFICE_XLSX = "xlsx";
    /**
     * office中.ppt格式
     */
    public static final String OFFICE_PPT = "ppt";
    /**
     * office中.pptx格式
     */
    public static final String OFFICE_PPTX = "pptx";
    /**
     * pdf格式
     */
    public static final String OFFICE_TO_PDF = "pdf";

    public static void main(String[] args) {
        Office2PDF office2pdf = new Office2PDF();
        office2pdf.openOfficeToPDF("E:\\Workspaces\\MyEclipse2013\\DataTemp\\baiduwenkuModel\\test002." + OFFICE_DOC, "E:\\Workspaces\\MyEclipse2013\\DataTemp\\baiduwenkuModel\\test002_" + new Date().getTime() + "." + OFFICE_TO_PDF);

    }

    /**
     * 使Office全部格式的文档转化为pdf文件
     * 
     * @param inputFilePath  源文件路径,
     * @param outputFilePath  目标文件路径,
     * @return
     */
    public boolean openOfficeToPDF(String inputFilePath, String outputFilePath) {
        return office2pdf(inputFilePath, outputFilePath);
    }

    /**
     * 根据操作系统的名称,获取OpenOffice.org 3的安装目录<br>
     * 如我的OpenOffice安装在:D:/Program Files (x86)/OpenOffice 4<br>
     * 
     * @return OpenOffice.org 3的安装目录
     */
    public String getOfficeHome() {
        String osName = System.getProperty("os.name");
        if (Pattern.matches("Linux.*", osName)) {
            return "/opt/openoffice.org3";
        } else if (Pattern.matches("Windows.*", osName)) {
            return "D:\\Program Files (x86)\\OpenOffice 4";
        } else if (Pattern.matches("Mac.*", osName)) {
            return "/Application/OpenOffice.org.app/Contents";
        }
        return null;
    }

    /**
     * 连接OpenOffice.org 并且启动OpenOffice.org
     * 
     * @return
     */
    public OfficeManager getOfficeManager() {
        DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();
        // 获取OpenOffice.org 3的安装目录
        String officeHome = getOfficeHome();
        config.setOfficeHome(officeHome);
        // 启动OpenOffice的服务
        OfficeManager officeManager = config.buildOfficeManager();
        officeManager.start();
        return officeManager;
    }

    /**
     * 转换文件
     * 
     * @param inputFile
     * @param outputFilePath_end
     * @param inputFilePath
     * @param outputFilePath
     * @param converter
     */
    public void converterFile(File inputFile, String outputFilePath_end, String inputFilePath, String outputFilePath, OfficeDocumentConverter converter) {
        File outputFile = new File(outputFilePath_end);
        // 假如目标路径不存在,则新建该路径
        if (!outputFile.getParentFile().exists()) {
            outputFile.getParentFile().mkdirs();
        }
        converter.convert(inputFile, outputFile);
        System.out.println("文件:" + inputFilePath + "\n转换为\n目标文件:" + outputFile + "\n成功!");
    }

    /**
     * 使Office全部格式的文档 转化为pdf文件<br>
     * 
     * @param inputFilePath
     *            源文件路径,如:"E:\\Workspaces\\MyEclipse2013\\DataTemp\\baiduwenkuModel\\test001.docx
     * @param outputFilePath
     *            目标文件路径,如:"E:\\Workspaces\\MyEclipse2013\\DataTemp\\baiduwenkuModel\\test001.pdf"
     * @return
     */
    public boolean office2pdf(String inputFilePath, String outputFilePath) {
        boolean flag = false;
        OfficeManager officeManager = getOfficeManager();
        // 连接OpenOffice
        OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
        long begin_time = new Date().getTime();
        if (null != inputFilePath) {
            File inputFile = new File(inputFilePath);
            // 判断目标文件路径是否为空
            if (null == outputFilePath) {
                // 转换后的文件路径
                String outputFilePath_end = getOutputFilePath(inputFilePath);
                if (inputFile.exists()) {// 找不到源文件, 则返回
                    converterFile(inputFile, outputFilePath_end, inputFilePath, outputFilePath, converter);
                    flag = true;
                }
            } else {
                if (inputFile.exists()) {// 找不到源文件, 则返回
                    converterFile(inputFile, outputFilePath, inputFilePath, outputFilePath, converter);
                    flag = true;
                }
            }
            officeManager.stop();
        } else {
            System.out.println("con‘t find the resource");
        }
        long end_time = new Date().getTime();
        System.out.println("文件转换耗时:[" + (end_time - begin_time) + "]ms");
        return flag;
    }

    /**
     * 获取输出文件
     * 
     * @param inputFilePath
     * @return
     */
    public String getOutputFilePath(String inputFilePath) {
        String outputFilePath = inputFilePath.replaceAll("." + getPostfix(inputFilePath), ".pdf");
        return outputFilePath;
    }

    /**
     * 获取inputFilePath的后缀名,如:"e:/test.pptx"的后缀名为:"pptx"<br>
     * 
     * @param inputFilePath
     * @return
     */
    public String getPostfix(String inputFilePath) {
        return inputFilePath.substring(inputFilePath.lastIndexOf(".") + 1);
    }

}
bubuko.com,布布扣

第二步:PDF(OpenOffice+JodConverter)=>SWF(pdf2swf)

1.下载SWFTools

下载地址http://www.swftools.org/download.html

我下载的是:swftools-2012-10-15-1307.exe

2.安装SWFTools

3:源码(一下有两种方式)

源码1

 

bubuko.com,布布扣
  1 package com.wyh.toPdf;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.File;
  5 import java.io.IOException;
  6 import java.io.InputStream;
  7 import java.io.InputStreamReader;
  8 import java.util.Date;
  9 
 10 /**
 11  * PDF转SWF工具
 12  *  15  * 
 16  */
 17 public class PDF2SWF {
 18 
 19     /**
 20      * SWTOOLS的安装路径,我的SWFTools安装目录为:"D:\Program Files (x86)\SWFTools"
 21      */
 22     public static final String SWFTOOLS_PATH = "D:\\Program Files (x86)\\SWFTools";
 23     /**
 24      * pdf文件后缀名
 25      */
 26     public static final String FILE_NAME_OF_PDF = "pdf";
 27     /**
 28      * swf文件后缀名
 29      */
 30     public static final String FILE_NAME_OF_SWF = "swf";
 31 
 32     /**
 33      * 获得文件的路径
 34      * 
 35      * @param file
 36      *            文件的路径 ,如:"c:/test/test.swf"
 37      * @return 文件的路径
 38      */
 39     public static String getFilePath(String file) {
 40         String result = file.substring(0, file.lastIndexOf("/"));
 41         if (file.substring(2, 3) == "/") {
 42             result = file.substring(0, file.lastIndexOf("/"));
 43         } else if (file.substring(2, 3) == "\\") {
 44             result = file.substring(0, file.lastIndexOf("\\"));
 45         }
 46         return result;
 47     }
 48 
 49     /**
 50      * 新建一个目录
 51      * 
 52      * @param folderPath
 53      *            新建目录的路径 如:"c:\\newFolder"
 54      */
 55     public static void newFolder(String folderPath) {
 56         try {
 57             File myFolderPath = new File(folderPath.toString());
 58             if (!myFolderPath.exists()) {
 59                 myFolderPath.mkdir();
 60             }
 61         } catch (Exception e) {
 62             System.out.println("新建目录操作出错");
 63             e.printStackTrace();
 64         }
 65     }
 66 
 67     /**
 68      * the exit value of the subprocess represented by this Process object. By
 69      * convention, the value 0 indicates normal termination.
 70      * 
 71      * @param sourcePath
 72      *            pdf文件路径 ,如:"c:/hello.pdf"
 73      * @param destPath
 74      *            swf文件路径,如:"c:/test/test.swf"
 75      * @return 正常情况下返回:0,失败情况返回:1
 76      * @throws IOException
 77      */
 78     public static int convertPDF2SWF(String sourcePath, String destPath) throws IOException {
 79         // 如果目标文件的路径是新的,则新建路径
 80         newFolder(getFilePath(destPath));
 81 
 82         // 源文件不存在则返回
 83         File source = new File(sourcePath);
 84         if (!source.exists()) {
 85             return 0;
 86         }
 87 
 88         // 调用pdf2swf命令进行转换
 89         String command = SWFTOOLS_PATH + "/pdf2swf.exe  -t \"" + sourcePath + "\" -o  \"" + destPath + "\" -s flashversion=9 -s languagedir=D:\\xpdf\\xpdf-chinese-simplified ";
 90         System.out.println("命令操作:" + command + "\n开始转换...");
 91         // 调用外部程序
 92         Process process = Runtime.getRuntime().exec(command);
 93         final InputStream is1 = process.getInputStream();
 94         new Thread(new Runnable() {
 95             public void run() {
 96                 BufferedReader br = new BufferedReader(new InputStreamReader(is1));
 97                 try {
 98                     while (br.readLine() != null)
 99                         ;
100                 } catch (IOException e) {
101                     e.printStackTrace();
102                 }
103             }
104         }).start(); // 启动单独的线程来清空process.getInputStream()的缓冲区
105         InputStream is2 = process.getErrorStream();
106         BufferedReader br2 = new BufferedReader(new InputStreamReader(is2));
107         // 保存输出结果流
108         StringBuilder buf = new StringBuilder();
109         String line = null;
110         while ((line = br2.readLine()) != null)
111             // 循环等待ffmpeg进程结束
112             buf.append(line);
113         while (br2.readLine() != null)
114             ;
115         try {
116             process.waitFor();
117         } catch (InterruptedException e) {
118             e.printStackTrace();
119         }
120         System.out.println("转换结束...");
121         return process.exitValue();
122     }
123 
124     /**
125      * pdf文件转换为swf文件操作
126      * 
127      * @param sourcePath
128      *            pdf文件路径 ,如:"c:/hello.pdf"
129      * @param destPath
130      *            swf文件路径,如:"c:/test/test.swf"
131      */
132     public static void pdf2swf(String sourcePath, String destPath) {
133         long begin_time = new Date().getTime();
134         try {
135             PDF2SWF.convertPDF2SWF(sourcePath, destPath);
136         } catch (Exception ex) {
137             System.out.println("转换过程失败!!");
138         }
139         long end_time = new Date().getTime();
140         System.out.println("转换共耗时 :[" + (end_time - begin_time) + "]ms");
141         System.out.println("转换文件成功!!");
142     }
143 
144     public static void main(String[] args) throws IOException {
145         String sourcePath = "E:\\Workspaces\\MyEclipse2013\\DataTemp\\baiduwenkuModel\\test002." + FILE_NAME_OF_PDF;
146         String destPath = "E:\\Workspaces\\MyEclipse2013\\DataTemp\\baiduwenkuModel\\test002_" + new Date().getTime() + "." + FILE_NAME_OF_SWF;
147         pdf2swf(sourcePath, destPath);
148     }
149 }

bubuko.com,布布扣

3:源码2:

bubuko.com,布布扣
  1 package com.wyh.toPdf;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.File;
  5 import java.io.IOException;
  6 import java.io.InputStreamReader;
  7 import java.util.ArrayList;
  8 import java.util.Date;
  9 import java.util.List;
 10 
 11  
 12 /**
 13  * @author nlb
 14  * @version 1.0 把pdf,jpeg,font,gif,pgn,wav转化为swf文件
 15  */ 
 16 public class ConvertToSwf { 
 17  
 18     private final String CONVERTFILETYPE = "pdf,jpg,jpeg,font,gif,png,wav"; 
 19     private String swftoolsPath; 
 20     /**
 21      * @param swftoolsPath
 22      *            用于进行把文件转化为swf的工具地址
 23      */ 
 24     public ConvertToSwf(String swftoolsPath) { 
 25         this.swftoolsPath=swftoolsPath; 
 26     } 
 27     /**
 28      * 把文件转化为swf格式支持"pdf,jpg,jpeg,font,gif,png,wav"
 29      * 
 30      * @param sourceFilePath
 31      *            要进行转化为swf文件的地址
 32      * @param swfFilePath
 33      *            转化后的swf的文件地址
 34      * @return
 35      */ 
 36     public boolean convertFileToSwf(String sourceFilePath, String swfFilePath) { 
 37         System.out.println("开始转化文件到swf格式");
 38         if (swftoolsPath == null || swftoolsPath == "") { 
 39            System.out.println("未指定要进行swf转化工具的地址!!!");
 40             return false; 
 41         } 
 42         String filetype = sourceFilePath.substring(sourceFilePath 
 43                 .lastIndexOf(".") + 1); 
 44         // 判读上传文件类型是否符合转换为pdf 
 45        System.out.println("判断文件类型通过");
 46         if (CONVERTFILETYPE.indexOf(filetype.toLowerCase()) == -1) { 
 47             System.out.println("当前文件不符合要转化为SWF的文件类型!!!");
 48             return false; 
 49         } 
 50         File sourceFile = new File(sourceFilePath); 
 51  
 52         if (!sourceFile.exists()) { 
 53             System.out.println("要进行swf的文件不存在!!!");
 54             return false; 
 55         } 
 56         System.out.println("准备转换的文件路径存在");
 57         if (!swftoolsPath.endsWith(File.separator)) { 
 58             swftoolsPath += File.separator; 
 59         } 
 60         StringBuilder commandBuidler = new StringBuilder(swftoolsPath); 
 61         File swfFile = new File(swfFilePath); 
 62         if (!swfFile.getParentFile().exists()) { 
 63             swfFile.getParentFile().mkdirs(); 
 64         } 
 65         if (filetype.toLowerCase().equals("jpg")) { 
 66             filetype = "jpeg"; 
 67         } 
 68         List<String>  command = new   ArrayList<String>();   
 69             command.add(this.swftoolsPath+"\\"+filetype.toLowerCase()+"2swf.exe");//从配置文件里读取     
 70             command.add("-z");     
 71             command.add("-s");     
 72             command.add("flashversion=9");     
 73             command.add("-s");     
 74             command.add("poly2bitmap");//加入poly2bitmap的目的是为了防止出现大文件或图形过多的文件转换时的出错,没有生成swf文件的异常     
 75             command.add(sourceFilePath);     
 76             command.add("-o");     
 77             command.add(swfFilePath);     
 78         try { 
 79             ProcessBuilder processBuilder = new ProcessBuilder();     
 80             processBuilder.command(command);     
 81             Process process = processBuilder.start();     
 82             System.out.println("开始生成swf文件..");
 83             dealWith(process); 
 84             try {     
 85                 process.waitFor();//等待子进程的结束,子进程就是系统调用文件转换这个新进程     
 86             } catch (InterruptedException e) {     
 87                 e.printStackTrace();     
 88             }     
 89             File swf = new File(swfFilePath); 
 90             if (!swf.exists()) { 
 91                 return false; 
 92             } 
 93             System.out.println("转化SWF文件成功!!!");
 94         } catch (IOException e) { 
 95             // TODO Auto-generated catch block 
 96             System.out.println("转化为SWF文件失败!!!");
 97             e.printStackTrace(); 
 98             return false; 
 99         } 
100  
101         return true; 
102     } 
103     public static void main(String[] args) { 
104         ConvertToSwf a=new ConvertToSwf("D:\\Program Files (x86)\\SWFTools"); 
105         long begin_time=new Date().getTime();
106         a.convertFileToSwf("E:\\Workspaces\\MyEclipse2013\\DataTemp\\baiduwenkuModel\\test002.pdf", "E:\\Workspaces\\MyEclipse2013\\DataTemp\\baiduwenkuModel\\test002_001.swf"); 
107         long end_time=new Date().getTime();
108         System.out.println("result:"+(end_time-begin_time));
109     } 
110     private void dealWith(final Process pro){     
111         // 下面是处理堵塞的情况     
112         try {     
113             new Thread(){     
114                 public void run(){     
115                     BufferedReader br1 = new BufferedReader(new InputStreamReader(pro.getInputStream()));     
116                     String text;     
117                     try {     
118                         while ( (text = br1.readLine()) != null) {     
119                             System.out.println(text);     
120                         }     
121                     } catch (IOException e) {     
122                         e.printStackTrace();     
123                     }     
124                 }     
125             }.start();     
126         } catch (Exception e) {     
127             e.printStackTrace();     
128         }     
129         try {     
130             new Thread(){     
131                 public void run(){     
132                     BufferedReader br2 = new BufferedReader(new InputStreamReader(pro.getErrorStream()));//这定不要忘记处理出理时产生的信息,不然会堵塞不前的     
133                     String text;     
134                     try {     
135                         while( (text = br2.readLine()) != null){     
136                             System.err.println(text);     
137                         }     
138                     } catch (IOException e) {     
139                         e.printStackTrace();     
140                     }     
141                 }     
142             }.start();     
143         } catch (Exception e) {     
144             e.printStackTrace();     
145         }     
146     }     
147 } 
bubuko.com,布布扣

最后:

1.下载flexpaper

下载地址:http://code.google.com/p/flexpaper/downloads/list

下载:FlexPaper_2.0.2.zip

2.然后解压,需要的文件如下:

bubuko.com,布布扣

上面是我重新组合的,你也可以把解压缩文件夹整个的拷贝到WebRoot下面。

不过路径在设置的时候,就需要注意啦.....

3.新建一个jsp文件

index.jsp

bubuko.com,布布扣
1 <%@ page contentType="text/html; charset=utf-8"%>
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 <html>
     <head>
         <title>showWenKU</title>
         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 
         <script type="text/javascript"
             src="${pageContext.request.contextPath}/flexpaper/swfobject/swfobject.js"></script>
         <script type="text/javascript"
             src="${pageContext.request.contextPath}/flexpaper/flexpaper_flash.js"></script>
 
         <script type="text/javascript"> 
             <!-- For version detection, set to min. required Flash Player version, or 0 (or 0.0.0), for no version detection. --> 
             var swfVersionStr = "9.0.124";
             <!-- To use express install, set to playerProductInstall.swf, otherwise the empty string. -->
             var xiSwfUrlStr = "${expressInstallSwf}";
             var flashvars = { 
                   SwfFile : escape("${pageContext.request.contextPath}/flexpaper/swf/test_1352107155307_1352172932517.swf?v1.4.0final"),
                   Scale : 0.8, //放大因子,是一个0以上的数(带小数 1 = 100%) 。
                   ZoomTransition : "easeOut",//光学变焦过渡,默认值是easeOut,可取值: easenone, easeout, linear, easeoutquad
                   ZoomTime : 0.5, //时间过渡让变焦达到新的放大因子,值为0或更大的数。
                     ZoomInterval : 0.1,//区间的滑动缩放。放大因子缺省值是0.1。如同在工具栏上使用滑动条按钮的效果。
                     FitPageOnLoad : true, //(布尔) 适合初始页大小(依高度而定)的装载页。如同在工具栏上使用fit-page按钮的效果。
                     FitWidthOnLoad : true, // (布尔)适合初始页宽度大小的装载页。如同在工具栏上使用fit-width按钮的效果。
                     PrintEnabled : true,   //是否支持打印
                     FullScreenAsMaxWindow :false,  //是否支持全屏
                   ProgressiveLoading : false,  //是否支持延迟加载
                   SearchMatchAll : true,//设置为true时,单击搜索所有符合条件的地方高亮显示
                   PrintToolsVisible : false,
                     ViewModeToolsVisible : true,//(布尔)显示或隐藏视图模式与工具栏
                     ZoomToolsVisible : true,//(布尔) 从工具栏显示或隐藏变焦工具
                     FullScreenVisible : true,//(布尔)以最大化方式打开一个新浏览器窗口。
                     NavToolsVisible : true,//(布尔)显示或隐藏导航工具
                     CursorToolsVisible : false,//(布尔) 显示或隐藏光标工具
                     SearchToolsVisible : true,
                     localeChain: "en_US" //语言
                   };
              var params = {
                 
                 }
             params.quality = "high";
             params.bgcolor = "#ffffff";
             params.allowscriptaccess = "sameDomain";
             params.allowfullscreen = "true";
             var attributes = {};
             attributes.id = "FlexPaperViewer";
             attributes.name = "FlexPaperViewer";
             swfobject.embedSWF(
                 "${pageContext.request.contextPath}/flexpaper/swf/FlexPaperViewer.swf", "flashContent", 
                 "800", "532", 
                 swfVersionStr, xiSwfUrlStr, 
                 flashvars, params, attributes);
             swfobject.createCSS("#flashContent", "display:block;text-align:left;");
         </script>
 
     </head>
     <body>
         <div id="flashContent" ></div>
     </body>
 </html>
bubuko.com,布布扣

 

具体的参数可以参考:

官方文档1:http://flexpaper.org/docs_api.jsp

官方文档2:http://flexpaper.org/docs_parameters.jsp

声明:

Articles from:http://www.cnblogs.com/hongten/archive/2012/11/06/java_FlexPaper.html

 

模仿百度文库,布布扣,bubuko.com

模仿百度文库

标签:des   style   blog   class   code   java   

原文地址:http://www.cnblogs.com/w647081/p/3709834.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!