当前位置: 移动技术网 > 移动技术>移动开发>Android > 微信或手机浏览器在线显示office文件(已测试ios、android)

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

2019年07月24日  | 移动技术网移动技术  | 我要评论

最近开发微信企业号,发现微信andriod版内置浏览器在打开文件方面有问题,但是ios版没有问题,原因是ios版使用的是safari浏览器 支持文档直接打开,但是andriod版使用的是腾讯浏览器x5内核,不知道什么原因不支持,可能是集成出现的问题,这里提供解决方法,这种方法也同样适用手机浏览器或者安卓开发。通过此方法可以在微信上开发自己的第三方应用,或者解决自己的项目问题,解决方法及核心代码如下:
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文件,并读取内容-------------------------

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;

 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网