java实现在线文档浏览

目前发现两种方法:

1、使用openoffice将office转换为pdf文档,使用swfTools将pdf文档转换为swf文件,通过flexpaper插件展示;

2、webOffice插件,直接展示。

在这里先说下第一种:

 第一  office--->pdf

  下载 openoffice  地址: https://share.weiyun.com/e78f8f6518e3a5534044b210102daebd   密码: sM0YCz

  然后在cmd环境下进入安装目录的program目录,输入打开openoffice的命令:

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

  输入完成之后在任务管理器可以看见soffice.bin的进程在任务管理器,这一服务就启动成功。当然在代码中转换office2pdf我们还需要一些架包。

  下载jodconverter-2.2.2架包,然后复制到lib目录下,引入架包就可以了。这个架包有如下包:

  如果报错 The type com.sun.star.lang.XEventListener cannot be resolved. It is indirectly referenced from required异常:

  解决办法:到官方网站下载jodconverter-2.2.2.zip,然后把lib文件夹下得所有jar包都拷进去,就可以了。

package com.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
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;
import com.winchannel.pluginclient.util.PropertiersUtil;

/**
 * @author xx
 * @time xx
 */
public class ConvertPdf {
    
      /** 
     * @param filePath  上传文件所在文件夹的绝对路径 
     * @param fileName  文件名称 
     * @return 生成pdf路径\文件名 
     */  
    public String beginConvert(String filePath,  String fileName,String fastName) {  
        final String DOC = ".doc";  
        final String DOCX = ".docx";  
        final String XLS = ".xls";  
        final String XLSX = ".xlsx";  
        final String PDF = ".pdf";  
        final String PPT=".ppt";
        final String PPTX=".pptx";
        final String TXT=".txt";
        String fileExt = "";  
        if (null != fileName && fileName.indexOf(".") > 0) {  
            int index = fileName.lastIndexOf(".");
            fileExt = fileName.substring(index).toLowerCase();  
        }  
        String inputFile = filePath + File.separator + fileName;  
        String outputFile = "";  
        int i = 0;
        //如果是office文档,先转为pdf文件  
        if (fileExt.equals(DOC) || fileExt.equals(DOCX) || fileExt.equals(XLS)  
                || fileExt.equals(XLSX)|| fileExt.equals(PPT)  
                || fileExt.equals(PPTX)){ 
            
           outputFile = filePath + File.separator + fastName + PDF;  
           System.out.println("====源文件!===="+inputFile);
           System.out.println("====转换后文件!===="+outputFile);
           i= office2PDF(inputFile, outputFile);  
        }  
        if(fileExt.equals(TXT)||fileExt.equals(".java")){
                File input=new File(inputFile);
              ChangeFileCode changeFileCode = new ChangeFileCode();  
            String fileCode = changeFileCode.getFileEnCode(inputFile); 
            if(fileCode!=null && !"".equals(fileCode)) {
                changeFileCode.setFileIn(input.getPath(), fileCode);//如果文件编码为ANSI用GBK来读,如果是UTF-8用UTF-8来读  
                changeFileCode.setFileOut(input.getPath(), "UTF-8");//UTF-8则文件编码为UTF-8, 如果为GBK,编码为ANSI  
                changeFileCode.start();  
            }
              inputFile=filePath + File.separator + fastName + ".odt";  
              input.renameTo(new File(inputFile));
              outputFile=filePath + File.separator + fastName + PDF;  
              System.out.println("====源文件!===="+inputFile);
              System.out.println("====转换后文件!===="+outputFile);
              i=office2PDF(inputFile, outputFile);
        }
        if(fileExt.equals(PDF)){//如果是pdf不需要转换 复制改名
            outputFile = filePath + File.separator + fastName + PDF;  
            i=copy(new File(inputFile),new File(outputFile));
        }
    
        if(i==0){
            return outputFile;
        }else{
            return "0";
        }
    } 
    
    /**
     * 复制文件
     */
    private int copy(File fromFile, File toFile){ 
        try {
            if (!fromFile.exists()){
                  System.out.println("====来源文件为空!====");
               }
               if (!toFile.exists()){
                   System.out.println("====创建新文件!====");
                  toFile.createNewFile();
               }
               FileInputStream  fis = new FileInputStream(fromFile);
                System.out.println("fromFile :" + fromFile.getAbsolutePath());
               FileOutputStream fos = new FileOutputStream(toFile);
                System.out.println("toFile :" + toFile.getAbsolutePath());
         
               int len = 0; 
               byte[] buf = new byte[1024]; 
               while((len = fis.read(buf)) != -1){ 
                   fos.write(buf,0,len); 
               }
               
               fis.close(); 
               fos.close(); 
        } catch (Exception e) {
            System.out.println("====文件复制失败====");
            return -1; 
        }
        return 0;
       
    } 

    /** 
     * office文档转pdf文件 
     * @param sourceFile    office文档绝对路径 
     * @param destFile      pdf文件绝对路径 
     * @return 
     */  
    public int office2PDF(String sourceFile, String destFile) {  
         String OpenOffice_HOME = PropertiersUtil.getValue("base", "oo_home");
         String host_Str =PropertiersUtil.getValue("base", "oo_host");
         String port_Str = PropertiersUtil.getValue("base", "oo_port");
         OpenOfficeConnection connection=null;
         Process pro =null;
         try {  
             File inputFile = new File(sourceFile);  
             if (!inputFile.exists()) {  
                 System.out.println("====找不到源文件===="+sourceFile);
                 return -1; // 找不到源文件   
             }  
             // 如果目标路径不存在, 则新建该路径    
             File outputFile = new File(destFile);  
             if (!outputFile.getParentFile().exists()) {  
                 outputFile.getParentFile().mkdirs();  
             }  
             //windows
             // 启动OpenOffice的服务    
             String command = OpenOffice_HOME  
                     + "\\program\\soffice.exe -headless -accept=\"socket,host="  
                     + host_Str + ",port=" + port_Str + ";urp;\"";  
            //linux
          /*   String command = openOffice_HOME  
                     + "/program/soffice --headless --accept=\"socket,host="  
                     + host_Str + ",port=" + port_Str + ";urp;\"  --nofirststartwizard &"; */
                      
             System.out.println("====command===="+command);
             pro = Runtime.getRuntime().exec(command);  
             // 连接openoffice服务  
             connection = new SocketOpenOfficeConnection(host_Str, Integer.parseInt(port_Str));  
             connection.connect();  
             // 转换   
             DocumentConverter converter = new OpenOfficeDocumentConverter(connection);  
             try{
                 converter.convert(inputFile, outputFile);  
             }catch (Exception e) {
                 if(connection!=null){
                     connection.disconnect();  
                 }
                 if(pro!=null){
                     pro.destroy();  
                 }
                 System.out.println("====转换异常!====");
             }
             // 关闭连接和服务  
             connection.disconnect();  
             pro.destroy();  
   
             return 0;  
         } catch (FileNotFoundException e) { 
             System.out.println("====文件未找到====");
             return -1;  
         } catch (ConnectException e) {  
             System.out.println("====OpenOffice服务监听异常!====");
         } catch (IOException e) {
             System.out.println("====IO异常!====");
         } 
         return 1;  
    }  
    
    
    public static void main(String[] args) throws IOException {  
        ConvertPdf c=new ConvertPdf();
        String filePath="E:\\";
        String fileName="ddd.docx";
        System.out.println(">>>"+c.beginConvert(filePath, fileName,"1"));
    }  
}

第二 pdf--->swf

 下载 swftools 地址: https://share.weiyun.com/653b5ad04d9132347c3a72af9e5da6d1   密码: 77NIZe

package com.util;  
  
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
      
/** 
 * 将pdf文件转成swf格式 
 */  
public class ConvertSwf {  
    private final Logger log = LoggerFactory.getLogger(ConvertSwf.class);

    /** 
     * 将pdf文件转换成swf文件 
     * @param sourceFile pdf文件绝对路径 
     * @param outFile    swf文件绝对路径 
     * @param toolFile   转换工具绝对路径 
     */  
    public String convertPdf2Swf(String sourceFile, String outFile) {  
        //linux
    //    String TOOL = "pdf2swf";  
        //windows
        String TOOL = "D:\\Program Files (x86)\\SWFTools\\pdf2swf";  
        String command = TOOL  +" "+ sourceFile + " -o " + outFile  
                 + " -s flashversion=9 "+ " -p 0-100"+" -s languagedir=/opt/xpdf-chinese-simplified/  ";  
        try {  
            Process process = Runtime.getRuntime().exec(command);  
            log.info("===="+loadStream(process.getInputStream())+"====");
            log.info("===="+loadStream(process.getErrorStream())+"====");
            log.info("====转换成功swf====");
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return "";
    }  
  
    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();  
    }  
    public static void main(String[] args) {
        ConvertSwf c = new ConvertSwf();
        String filePath="E:\\";
    String fileName="1.pdf";
        c.convertPdf2Swf(filePath+fileName,filePath+"12.swf");
    }
}  

第三 展示swf

 下载 flexpaper  地址:https://share.weiyun.com/298067f3edba681973d89a9487ce78a0   密码:NXwFPi

 使用这个插件需要有三个js文件。分别是:jquery.js、flexpaper_flash.js、flexpaper_flash_debug.js。插件的名字是FlexPaperViewer.swf。

<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html;charset=UTF-8" http-equiv="Content-Type">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/flexpaper_flash.js"></script>
<script type="text/javascript" src="js/flexpaper_flash_debug.js"></script>
<style type="text/css" media="screen">
html,body{
        height: 100%;
}
body{
        margin: 0;
        padding: 0;
        overflow: auto;
}
#flashContent{
       display: none;
}
</style>
<title>在线文档预览</title>
</head>
<body >
   <div style="position: absolute; left:50px;top:10px;">
        <a id="viewerPlaceHolder" style="width: 820px;height: 650px;display: block;"></a>
          <script type="text/javascript">
           var fp=new FlexPaperViewer(
                   'FlexPaperViewer',
                   'viewerPlaceHolder',
                   {
                       config:{
                           SwfFile:escape('http://localhost:8080/TestBaiDu/12.swf'),
                           Scale:1.2,              
                            ZoomTransition:'easeOut',
                            ZoomTime:0.5,
                            ZoomInterval:0.2,
                            FitPageOnLoad:false,
                            FitWidthOnload:false,
                            FullScreenAsMaxWindow:false,
                            ProgressiveLoading:false,
                            MinZoomSize:0.2,
                            MaxZoomSize:5,
                            SearchMatchAll:false,
                            InitViewMode:'SinglePage',
                            RenderingOrder : 'flash',
                            ViewModeToolsVisible:true,
                            ZoomToolsVisible:true,
                            NavToolsVisible:true,
                            CursorToolsVisible:true,
                            SearchToolsVisible:true,
                            localeChain:'en_US'
                        }
                   });
          </script>
   </div>
</body>
</html>

注意问题:

1、在线预览只能实现10页的情况,需要把RenderingOrder : 'flash',设置为flash才可以实现超过10页的在线预览。

2、发现错误一般是openoffice服务没有开启。

3、Linux环境下会存在中文乱码的问题,是linux下不像windows支持那么多字体,需要安装多的字体,并且把字体所在位置链接到flexpaper所在位置。在使用pdf2swf加上参数-s languagedir=/usr/local/xpdf-chinese-simplified/

 

扩展:

<script type="text/javascript">  
        //判断是否是触屏(移动设备)  
        $.get((!window.isTouchScreen) ? '/UI_flexpaper_desktop_flat.html'  
                : '/UI_flexpaper_mobile_flat.html', function(toolbarData) {  
            $('#documentViewer').FlexPaperViewer({  
                config : {  
                    //swf文件的分页模式  
                    //SwfFile : "/flex/view/{Paper_[*,0].swf,28}",  
                    //单swf文件模式  
                    SwfFile : "/flex/view?name=Paper.swf",  
                    //JSONFile : '/flex/view?name=Paper.js',  
                    //pdf文件模式  
                    //PDFFile : '/flex/view?name=Paper.pdf',  
                    //初始缩放比例  
                    Scale : 0.6,  
                    //变焦模式一般都是'easeOut'  
                    ZoomTransition : 'easeOut',  
                    //变焦速度  
                    ZoomTime : 0.5,  
                    //变焦间隔  
                    ZoomInterval : 0.2,  
                    ///适应加载  
                    FitPageOnLoad : true,  
                    //适应宽度加载  
                    FitWidthOnLoad : false,  
                    FullScreenAsMaxWindow : false,  
                    ProgressiveLoading : true,  
                    //最小比例  
                    MinZoomSize : 0.2,  
                    //做大比例  
                    MaxZoomSize : 5,  
                    SearchMatchAll : true,  
                    //切换显示模式:Two Page双页/Portrait单页  
                    InitViewMode : 'Portrait',  
                    //加载方式  
                    RenderingOrder : 'flash',  
                    //显示模式(单/双页)按钮  
                    ViewModeToolsVisible : true,  
                    //缩放条  
                    ZoomToolsVisible : true,  
                    //页面跳转框  
                    NavToolsVisible : true,  
                    //焦点按钮  
                    CursorToolsVisible : true,  
                    //搜索栏  
                    SearchToolsVisible : true,  
                    //通过请求的方式获取的导航栏(响应式)  
                    Toolbar : toolbarData,  
                    //底部工具栏(用于注释的添加删除等)  
                    BottomToolbar : '/UI_flexpaper_annotations.html',  
                    WMode : 'window',  
                    //按钮提示语言  
                    localeChain : "zh_CN",  
                }  
            });  
        });  
    </script>  
页数跳转:$FlexPaper("documentViewer").gotoPage(5);
适应控件宽度:$FlexPaper("documentViewer").fitWidth();
适应控件高度:$FlexPaper("documentViewer").fitHeight();
获取当前页数:$FlexPaper("documentViewer").getCurrPage();
打印:$FlexPaper("documentViewer").printPaper();
下一页:$FlexPaper("documentViewer").nextPage();
上一页:$FlexPaper("documentViewer").prevPage();
搜索:$FlexPaper("documentViewer").searchText("");
切换显示模式:Two Page双页/Portrait单页
$FlexPaper("documentViewer").switchMode("Portrait");

SwfFile (字符串) 

flash文件FlexPaper应该开放 

JSONFile (字符串) 

json文档FlexPaper应该开放。 马克的页码{页面}如果你加载FlexPaper分裂模式(例如Paper.pdf_ {页面} . js)。 这只适用于FlexPaper AdaptiveUI启用。 

IMGFiles (字符串) 

页面的图片FlexPaper应该开放。 与{页面}标记页码(如Paper.pdf_ {页面} . png })。 这只适用于FlexPaper AdaptiveUI启用。 

规模 (数量) 

应该使用的初始缩放因子。 应该是一个数量以上0(1 = 100%) 

ZoomTransition (字符串) 

时应该使用的缩放转换放大FlexPaper。 它使用相同的过渡模式作为中间人。 默认值是easeOut。 一些例子:easenone easeout,线性,easeoutquad 

ZoomTime (数量) 

变焦的时候应该达到新的缩放因子。 应该是0或更大。 

ZoomInterval (数量) 

缩放滑块应该使用的间隔。 基本上每个之间的“一步”应该多大放大因子。 默认值是0.1。 应该是一个正数。 

FitPageOnLoad (布尔) 

适合在初始加载的页面。 同样的效果使用适合页面按钮的工具栏。 

FitWidthOnLoad (布尔) 

适合在初始加载宽度。 同样的效果使用fit-width按钮的工具栏。 

localeChain (字符串) 

设置要使用的语言环境(语言)。 目前支持以下语言: 


en_US(英语) 
fr_FR(法国) 
zh_CN(中文,简单) 
es_ES(西班牙语) 
pt_BR(巴西葡萄牙) 
ru_RU(俄罗斯) 
fi_FN(芬兰) 
de_DE(德国) 
设置nl_NL(荷兰) 
tr_TR(土耳其) 
se_SE(瑞典) 
pt_PT(葡萄牙) 
el_EL(希腊) 
dn_DN(丹麦) 
cz_CS(捷克) 
it_IT(意大利语) 
pl_PL(波兰) 
pv_FN(芬兰) 
hu_HU(匈牙利) 

FullScreenAsMaxWindow (布尔) 

使用此设置为true,点击全屏和FlexPaper将打开一个新的浏览器窗口最大化而不是使用真正的全屏。 这是首选设置当使用FlexPaper一样闪光独立的安全限制flash player禁用(出于安全原因)的大部分输入控件在真正的全屏。 

ProgressiveLoading (布尔) 

将逐步加载和显示文档设置为true时相对于之前下载完整的文档显示页面。 文档至少需要转换为Flash版本9为此(- t 9国旗使用PDF2SWF)。 请注意,这个参数没有影响FlexPaper锌。 请使用分割页面加载FlexPaper锌的大型文档。 

MaxZoomSize (数量) 

设置最大允许缩放级别 

MinZoomSize (数量) 

集的最小允许缩放级别 

SearchMatchAll (布尔) 

当该值设置成真时,观众强调所有匹配文档中执行搜索时。 

InitViewMode (字符串) 

设置启动视图模式。 例如“肖像”或“TwoPage”。 

PrintPaperAsBitmap (布尔) 

当该值设置成真时,观众将打印文档作为一个位图与矢量化 

StartAtPage (数量) 

让观众从一个特定的页面 

ViewModeToolsVisible (布尔) 

显示或隐藏工具栏的视图模式 

ZoomToolsVisible (布尔) 

显示或隐藏缩放工具栏的工具 

NavToolsVisible (布尔) 

显示或隐藏工具栏导航工具 

CursorToolsVisible (布尔) 

光标显示或隐藏工具栏的工具 

SearchToolsVisible (布尔) 

显示或隐藏工具栏的搜索工具 

jsDirectory (字符串) 

集提供的javascript目录的位置。 这只适用于FlexPaper AdaptiveUI启用。 

cssDirectory (字符串) 

设置css提供目录的位置。 这只适用于FlexPaper AdaptiveUI启用。 

localeDirectory (字符串) 

设置语言环境提供目录的位置。 这只适用于FlexPaper AdaptiveUI启用。 

 

感谢 :

   https://www.cnblogs.com/warrior4236/p/5866310.html

      https://www.cnblogs.com/liaoweipeng/p/4767660.html

   http://blog.csdn.net/u010392801/article/details/49464657
   http://blog.csdn.net/long5693525/article/details/50515610

转载于:https://www.cnblogs.com/start-fxw/p/5853519.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值