word文档在页面上浏览,类似百度文库形式

1、服务器上已经上传有需要的word文档,目前需要做的是将word文档按百度文库的样子显示在页面上,直接显示不可以,需要两个软件,openoffice和swftools工具,其中openoffice安装在C:/Program File/OpenOffice 4/下,启动openoffice服务是在cmd窗口中

进入OpenOffice 4/program 目录下:

soffice –headless –accept=”socket,host=127.0.0.1,port=8100;urp;”–nofirststartwizard&

回车,虽然没有反馈,但是服务启动了。

Swftools工具安装目录:C:/Program Files (x86)/swftools   ------------程序中需要使用到路径。

上面是使用的控件,准备完成。

2、jar包:需要的jar包:slf4j-api-1.5.6.jar 和 slf4j-log4j12-1.5.6.jar.

3、下面是FileConverterService.java类 :

作用:专门转换word到pdf,再转pdf到swf格式,在jsp页面调用。

文件名中如果有空格要去掉,有空格不可以完成转换。

package com.sjq.dwjs.service.fileConverter;
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;  
  
/** 
 * doc docx格式转换 
 */  
public class FileConverterService {
    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 FileConverterService(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(".")).trim();  
        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("C:/Program Files (x86)/swftools/pdf2swf.exe "+  
pdfFile.getPath() + " -o "+ swfFile.getPath() + " -T 9");  
                        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");  
            }  
        }  
    }  
  
}  

4、tomcat服务器上的word文档存放在WebRoot/upload下

Jbxx.jsp存储路径WebRoot/jsp/wlxy/Jbxx.jsp

Display.jsp 存储路径 WebRoot/jsp/wlxy/Display.jsp

5、Jbxx.jsp如下:

<%
try{
String sql = "select id,wjmc from 表名 where glid = '"+id+"' ";
	rs1 = stmt1.executeQuery(sql);
	while(rs1.next()){
		t_fjid = blanknull(rs1.getString("id"));
		wjmc = blanknull(rs1.getString("wjmc"));									out.println("<tr><td align='left' style='font-size:10pt;padding-bottom:10px;' >");
out.println("<a href=\"javascript:displayFj('"+wjcclj+"')\">"+wjmc+"</a>   ");
}
rs1.close();
}catch(Exception e){
	e.printStackTrace();		
}
wjcclj = application.getRealPath("/")+"upload\\"+wjcclj.replace("+","%20");
//这样得到的路径是word的实际路径:D:\tomcat_dwjs\webapps\upload\word文档名称.docx
FileConverterService d = new FileConverterService(wjcclj); 
//调用FileConverterService.java类中的conver方法开始转换,先执行doc2pdf()将office文件转换为pdf;再执行pdf2swf()将pdf转换为swf;  
d.conver();  
//调用getswfPath()方法,打印转换后的swf文件路径  
System.out.println(d.getswfPath());  
//生成swf相对路径,以便传递给flexpaper播放器  
swfpath = d.getswfPath();  
//将相对路径放入sessio中保存  
%>

6、Display.jsp页面如下:

要注意的是路径中文乱码。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.net.*"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<%
	String swfPath="";
	if(request.getParameter("swfPath")!=null&& !"".equals(request.getParameter("swfPath"))){
		swfPath=request.getParameter("swfPath");
		swfPath=URLDecoder.decode(swfPath,"UTF-8");
	}
	swfPath = basePath+"upload/"+swfPath;//重要,这样的路径是URL访问路径:http://10.23.23.43:88/dwjs/upload/word文档名称.docx
	System.out.println(swfPath+"!!!!!!!!!!!!!!!!");
 %>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>My JSP 'knowledge_displayFj.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type='text/javascript' src='../../js/swfobject.js'></script>
	<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>
  </head>
  
  <body>
    <div align="center">
  <div class="contentshow" style="margin-top:40px;">
		<div id='flashContent' style='text-align:center; padding-top:10px;'>
    	文件查看出!
		</div>
		
		    <script type='text/javascript'> 
                var swfVersionStr = '10.0.0';
                var xiSwfUrlStr = '../../js/expressInstall.swf';
               	var swfFile ='<%=swfPath%>';
                var flashvars = { 
                     ObjectID : 'FlexPaperViewer',
                     SwfFile : encodeURI(swfFile),
              		 Scale : 0.6, 
                     ZoomTransition : 'easeOut',
                     ZoomTime : 0.5,
		             ZoomInterval : 0.2,
		             FitPageOnLoad : true,
		             FitWidthOnLoad : true,
		             PrintEnabled : false,
		             FullScreenAsMaxWindow : false,
		             ProgressiveLoading : true,
		             localeChain: 'zh_CN'
                };
            				  
	             var params = {
          					
	             }
                params.quality = 'high';
                params.bgcolor = '#ffffff';
                params.allowscriptaccess = 'sameDomain';
                params.allowfullscreen = 'true';
                params.wmode = 'opaque';
                var attributes = {};
                attributes.id = 'FlexPaperViewer';
                attributes.name = 'FlexPaperViewer';
                swfobject.embedSWF('../../js/FlexPaperViewer.swf',
                		'flashContent','732', '550',
                		 swfVersionStr, xiSwfUrlStr,flashvars, params, attributes);
			    swfobject.createCSS('#flashContent', 'display:block;text-align:left;');
           	</script> 
           	
   </div>
   </div>
</body>
</html>

其中expressInstall.swf,FlexPaperViewer.swf文件可以在网上下载,存放路径:WebRoot/js/下。

需要的js包swfobject.js。








  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值