微信或手机浏览器在线显示office文件

1、判断浏览器类型

HttpServletRequest req = ServletActionContext.getRequest();
String userAgent=req.getHeader("User-Agent");//里面包含了设备类型

2、IOS版直接使用流输出

Andriod版利用openoffice+jod转换成html,然后对html内容重新编辑,文件中有图片的

将路径改为网络路径或者采用流输出(改成网络路径注意特殊符号,如+号会变成空格)

/**
* 从OA上抓取文件
* author 牟云飞
* company 海颐软件股份有限公司
* tel 15562579597
* qq 1147417467
* team 客服产品中心/于洋
* @return
*/
public String getFileFromOa(){ HttpServletRequest req = ServletActionContext.getRequest();
String userAgent=req.getHeader("User-Agent");//里面包含了设备类型
if(-1!=userAgent.indexOf("iPhone")){
//-----------------//
//此方法需要浏览器自己能够打开,ios可以但是微信andriod版内置浏览器不支持
//-----------------//
//如果是苹果手机
//获得文件地址
String fileUrl = ServletActionContext.getRequest().getParameter ("fileUrl");
fileUrl.replaceAll("%20", "\\+");//转换加号
String strURL = MessageUtil.oaUrl+fileUrl;
String fileType=strURL.substring(strURL.lastIndexOf(".")+1,strURL.length ());
//获得图片的数据流
try {
URL oaUrl = new URL(strURL);
HttpURLConnection httpConn = (HttpURLConnection) oaUrl.openConnection ();
InputStream in = httpConn.getInputStream();
//获取输出流
HttpServletResponse response = ServletActionContext.getResponse();
req.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String name=fileUrl.substring(fileUrl.lastIndexOf("/")+1, fileUrl.length()); response.setHeader("Content-Disposition",
"attachment;filename=" +
new String( (name ).getBytes(),
"iso-8859-1"));
if("doc".equals(fileType)||"docx".equals(fileType)){
response.setContentType("application/msword");
}else if("xls".equals(fileType)||"xlsx".equals(fileType)){
response.setContentType("application/msexcel");
}else{
response.setContentType("application/"+fileType);
}
OutputStream out = response.getOutputStream();
//输出图片信息
byte[] bytes = new byte[1024];
int cnt=0;
while ((cnt=in.read(bytes,0,bytes.length)) != -1) {
out.write(bytes, 0, cnt);
}
out.flush();
out.close();
in.close(); } catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}else{
//如果非苹果手机,自己处理文档 //获得文件地址
String fileUrl = ServletActionContext.getRequest().getParameter ("fileUrl"); fileUrl.replaceAll("%2B", "\\+");//转换加号
String strURL = MessageUtil.oaUrl+fileUrl;
//在本地存放OA文件,然后转换成html,再对文档中的图片路径进行修改,最后输出 到页面
try {
URL oaUrl = new URL(strURL);
HttpURLConnection httpConn = (HttpURLConnection) oaUrl.openConnection ();
InputStream in = httpConn.getInputStream();
//获取输出流
HttpServletResponse response = ServletActionContext.getResponse();
req.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String name=fileUrl.substring(fileUrl.lastIndexOf("/")+1, fileUrl.length()); //首先判断本地是否存在
String path=req.getRealPath("");
path=path.substring(0, path.lastIndexOf("\\")+1);
File htmlFile=new File(path + "OaFileToHtml\\"+name+".html");
if(!htmlFile.exists()){
//判断文件夹是否存在,创建文件夹
String oaFilePath=path + "OaFile";//存放OA文档的文件夹路径;
File oaFiles=new File(oaFilePath);
if(!oaFiles.exists()){
//如果文件夹不存在创建文件夹
oaFiles.mkdirs();
}
//将OA消息存入本地
File oafile=new File(oaFiles+ File.separator +name);
OutputStream out = new FileOutputStream(oafile);
//输出图片信息
byte[] bytes = new byte[1024];
int cnt=0;
while ((cnt=in.read(bytes,0,bytes.length)) != -1) {
out.write(bytes, 0, cnt);
}
out.flush();
out.close();
in.close();
//转换成html
String htmlFilePath =path + "OaFileToHtml";//OA文件转成html的位置
String htmlcontext=ConvertFileToHtml.toHtmlString(oafile, htmlFilePath);
req.setAttribute("htmlcontext", htmlcontext);
}else{
//已经存在转换成功的文档
StringBuffer htmlSb = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader (new FileInputStream(htmlFile),Charset.forName("gb2312")));
while (br.ready()) {
htmlSb.append(br.readLine());
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// HTML文件字符串
String htmlStr = htmlSb.toString();
//System.out.println("htmlStr=" + htmlStr);
// 返回经过清洁的html文本
req.setAttribute("htmlcontext", ConvertFileToHtml.clearFormat (htmlStr, ""));
} } catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "lookfile";
} }

  

-------------------将word转换成html文件,并读取内容-------------------------

此类借鉴原地址并修改http://jadethao.iteye.com/blog/1817738

package com.haiyisoft.wx.util;  

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern; 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; /**
* * 端口启动命令:
* soffice -headless -accept="socket,port=8100;urp;
*
*
* author 牟云飞
* company 海颐软件股份有限公司
* tel 15562579597
* qq 1147417467
* team 客服产品中心/于洋
*
*/
public class ConvertFileToHtml {
/**
* 将word文档转换成html文档
* @param docFile 需要转换的word文档
* @param filepath 转换之后html的存放路径
* @return 转换之后的html文件
*/
public static File convert(File docFile, String filepath) { // 创建保存html的文件
String fileName=docFile.getName();
File htmlFile = new File(filepath + "/" + fileName + ".html");
// 创建Openoffice连接
OpenOfficeConnection con = new SocketOpenOfficeConnection(8100);
try {
// 连接
con.connect();
} catch (ConnectException e) {
System.out.println("获取OpenOffice连接失败...");
e.printStackTrace();
} // 创建转换器
DocumentConverter converter = new OpenOfficeDocumentConverter(con);
// 转换文档问html
converter.convert(docFile, htmlFile);
// 关闭openoffice连接
con.disconnect();
return htmlFile;
} /**
*
* 将word转换成html文件,并且获取html文件代码。
* @param docFile 需要转换的文档
* @param filepath 文档中图片的保存位置
* @return 转换成功的html代码
*/
public static String toHtmlString(File docFile, String filepath) {
// 转换word文档
File htmlFile = convert(docFile, filepath);
System.out.println(htmlFile.getAbsolutePath());
// 获取html文件流
StringBuffer htmlSb = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(htmlFile),Charset.forName("gb2312")));
while (br.ready()) {
htmlSb.append(br.readLine());
}
br.close();
// 删除临时文件
//htmlFile.delete();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// HTML文件字符串
String htmlStr = htmlSb.toString();
//System.out.println("htmlStr=" + htmlStr);
// 返回经过清洁的html文本
return clearFormat(htmlStr, filepath);
} /**
*
* 清除一些不需要的html标记
*/ public static String clearFormat(String htmlStr, String docImgPath) { // 获取body内容的正则
String bodyReg = "<BODY .*</BODY>";
Pattern bodyPattern = Pattern.compile(bodyReg);
Matcher bodyMatcher = bodyPattern.matcher(htmlStr);
if (bodyMatcher.find()) {
// 获取BODY内容,并转化BODY标签为DIV
htmlStr = bodyMatcher.group().replaceFirst("<BODY", "<DIV").replaceAll ("</BODY>", "</DIV>");
} // 调整图片地址,这里将图片路径改为网络路径 htmlStr = htmlStr.replaceAll("<IMG SRC=\"../","<IMG SRC=\"" + MessageUtil.webUrl+"/******.do?action=***);
//特殊处理一下+号,因为网络传输+会变成空格,用%2B替换+号
String temp1=htmlStr.substring(htmlStr.indexOf("action=***"), htmlStr.length ());
String temp2=temp1.substring(0,temp1.indexOf("."));
String temp3=temp2.replaceAll("\\+", "%2B");
htmlStr=htmlStr.substring(0,htmlStr.indexOf ("action=***"))+temp3+temp1.substring(temp1.indexOf("."), temp1.length()); // 把<P></P>转换成</div></div>保留样式
// content = content.replaceAll("(<P)([^>]*>.*?)(<\\/P>)",
// "<div$2</div>");
// 把<P></P>转换成</div></div>并删除样式
htmlStr = htmlStr.replaceAll("(<P)([^>]*)(>.*?)(<\\/P>)", "<p$3</p>");
// 删除不需要的标签
htmlStr = htmlStr.replaceAll("<[/]?(font|FONT|span|SPAN|xml|XML|del|DEL|ins| INS|meta|META|[ovwxpOVWXP]:\\w+)[^>]*?>","");
// 删除不需要的属性
htmlStr = htmlStr.replaceAll("<([^>]*)(?:lang|LANG|class|CLASS|style|STYLE| size|SIZE|face|FACE|[ovwxpOVWXP]:\\w+)=(?:'[^']*'|\"\"[^\"\"]*\"\"|[^>]+)([^>]*)>","< $1$2>"); return htmlStr; }
}

  

 

在线显示office文件的更多相关文章

  1. 微信或手机浏览器在线显示office文件(已測试ios、android)

    近期开发微信企业号,发现微信andriod版内置浏览器在打开文件方面有问题,可是ios版没有问题.原因是ios版使用的是safari浏览器 支持文档直接打开.可是andriod版使用的是腾讯浏览器x5 ...

  2. openoffice+pdf2swf+FlexPaper在线显示office和pdf

    前提:本人的系统为Ubuntu 13.10 64位系统.本篇是我在配置好环境后一段时间写的,所以操作上可能会有也错误,因此仅供参考. 搜索在线显示office和pdf,最常见的方法就是把都转为swf, ...

  3. 织梦中在线显示pdf文件的方法

    如何在织梦中添加pdf文件并显示呢?下面这个教程将带领大家来操作.(注:手机版无法查看) 第一步:在系统-系统基本参数-附件设置中添加pdf格式 并且将大小调大 第二步:在核心-内容模型-普通文章中添 ...

  4. 在线浏览office 文件

    http://blog.csdn.net/binyao02123202/article/details/20051683 [Asp.net]常见word,excel,ppt,pdf在线预览方案,有图有 ...

  5. 在线读取office 文件(Word excel 等)

    https://view.officeapps.live.com/op/view.aspx?src=http://www.xxx.com/uploadfile/app/11.xls src 后面的网址 ...

  6. office文件在线预览,模仿网易邮箱在线预览的

    最近研究了半天,代码是倾情奉送啊,C#,asp.net的 这个原理是office文件转换为PDF文件,然后再转换成SWF文件,FlexPaper+swfTools. 有个问题,需要在web.confi ...

  7. Java实现word文档在线预览,读取office文件

    想要实现word或者其他office文件的在线预览,大部分都是用的两种方式,一种是使用openoffice转换之后再通过其他插件预览,还有一种方式就是通过POI读取内容然后预览. 一.使用openof ...

  8. 浏览器在线预览pdf、txt、office文件

    //使用文件预览的原因是:TMD微信浏览器屏蔽掉文件下载链接,只好折中使用文件在线预览功能//要点:1.office文件用微软的插件打开 http://view.officeapps.live.com ...

  9. 在线预览Office文件【效果类似百度文库】

    引言 结合上个项目和目前做的这个项目,其中都用到了Office文件在线预览,目前项目中是用到公司购买的Ntko控件,该控件每次浏览文件时则会提示安装信任插件,很繁琐,而且浏览效果不好. 提到Offic ...

随机推荐

  1. Testlink安装访问提示“应用程序DEFAULT WEB SITE”中的服务器错误

    错误摘要:HTTP错误403.14 - ForbiddenWeb服务器被配置为不列出此目录的内容.

  2. 我的Android进阶之旅------>Android中Dialog系统样式讲解

    今天在维护公司的一个APP的时候,有如下场景. 弹出一个AlertDialog的时候,在系统语言是中文的时候,如下所示: 弹出一个AlertDialog的时候,在系统语言是English的时候,如下所 ...

  3. 2、hive的基本操作

    1.创建数据库和表 1)创建数据库 hive> CREATE DATABASE IF NOT EXISTS userdb; OK Time taken: 0.252 seconds hive&g ...

  4. 修改mysql root的密码

    use mysql:update user set Password = Password('newPwd') where user='root';//更改root用户的密码flush privile ...

  5. docker daemon.json 配置

    下面是自己设置的 /etc/docker/daemon.json 文件中的配置案例 [root@master docker]# cat daemon.json { "registry-mir ...

  6. app开发需求文档怎么写

    我们在开发app前都会做需求分析,这个app开发需求文档怎么写呢?一般可以从这几点入手:确定APP方案的目标,APP方案的受众分析,APP开发方案功能设计,APP的操作系统说明方案,APP是是否是原生 ...

  7. django admin基础

    通过onetoonefiled扩展得到的不会在添加user是自动添加原因是onetoonefiled只是一个model 可以they are just Django models that happe ...

  8. rails 增删改查

    class InvoicesController < ApplicationController def index @invoices = Invoice.all end def show @ ...

  9. mysql安装配置 (单个mysql安装)

    mysql安装于 c盘因为有注册文件 和注册表 1.为了防止mysql数据表变大和sql日志增加   改变C:\ProgramData\MySQL\MySQL Server 5.7\my.ini 得指 ...

  10. linux下从源代码安装git的问题(install from source)

    安装环境:centos7.2 安装依赖包: yum install -y gcc .el7..x86_64 openssl-devel.x86_64 yum install -y curl.x86_6 ...