文章目录

  • 方案一:word转html
    • 1. 添加依赖
    • 2. 编写工具类Word2HtmlUtil.java
    • 3. 测试
  • 方案二:使用第三方服务
  • 方案三:使用微软 Office Online 服务
  • 永中文档预览服务详解
    • 1. 试一试在线预览!
    • 2. Web调用
    • 3. Java调用

方案一:word转html

使用Apache POI将word转为html,生成静态html,预览功能直接链接到html。

1. 添加依赖

<!-- word转html -->
<dependency><groupId>fr.opensagres.xdocreport</groupId><artifactId>fr.opensagres.xdocreport.document</artifactId><version>1.0.5</version>
</dependency>
<dependency><groupId>fr.opensagres.xdocreport</groupId><artifactId>org.apache.poi.xwpf.converter.xhtml</artifactId><version>1.0.5</version>
</dependency>
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.12</version>
</dependency>
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>3.12</version>
</dependency>

2. 编写工具类Word2HtmlUtil.java

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.List;import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.BasicURIResolver;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.FileURIResolver;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;public class Word2HtmlUtil {/*** 兼容doc和docx的word转html方法* @param inFile 需要转换的word文件* @param outPath 输出文件路径* @param outName 输出文件名*/public static void word2Html(String inFile, String outPath, String outName) throws Exception{FileInputStream fis=new FileInputStream(inFile);String suffix=inFile.substring(inFile.lastIndexOf("."));if (suffix.equalsIgnoreCase(".docx")) {docx2Html(fis, outPath, outName);} else {doc2Html(fis, outPath, outName);}}public static void docx2Html(InputStream fis, String outPath ,String outName) throws Exception{// 加载word文档生成 XWPFDocument对象XWPFDocument document = new XWPFDocument(fis);// 解析 XHTML配置String imageFolder = outPath + "images"+File.separator+"docx"+File.separator;//图片存放路径File imageFolderFile = new File(imageFolder);XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(imageFolderFile));options.setExtractor(new FileImageExtractor(imageFolderFile));options.setIgnoreStylesIfUnused(false);options.setFragment(true);options.URIResolver(new BasicURIResolver("images/docx/"));//html中img的src前缀// 将 XWPFDocument转换成XHTMLOutputStream out = new FileOutputStream(new File(outPath + outName));XHTMLConverter.getInstance().convert(document, out, options);}public static void doc2Html(InputStream fis, String outPath, String outName) throws Exception {HWPFDocument wordDocument = new HWPFDocument(fis);WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());wordToHtmlConverter.setPicturesManager(new PicturesManager() {public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {return "images/doc/" + suggestedName;// html中img的src值}});wordToHtmlConverter.processDocument(wordDocument);//保存图片List <Picture> pics = wordDocument.getPicturesTable().getAllPictures();if (pics != null) {for (int i = 0; i < pics.size(); i++) {Picture pic = (Picture) pics.get(i);try {String imageFolder = outPath + "images" + File.separator + "doc" + File.separator;File dir=new File(imageFolder);//图片保存路径if(!dir.exists()) {dir.mkdirs();}pic.writeImageContent(new FileOutputStream(imageFolder + pic.suggestFullFileName()));} catch (FileNotFoundException e) {e.printStackTrace();}}}Document htmlDocument = wordToHtmlConverter.getDocument();ByteArrayOutputStream out = new ByteArrayOutputStream();DOMSource domSource = new DOMSource(htmlDocument);StreamResult streamResult = new StreamResult(out);TransformerFactory tf = TransformerFactory.newInstance();Transformer serializer = tf.newTransformer();serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");serializer.setOutputProperty(OutputKeys.INDENT, "yes");serializer.setOutputProperty(OutputKeys.METHOD, "html");serializer.transform(domSource, streamResult);out.close();writeFile(new String(out.toByteArray()), outPath + outName);}public static void writeFile(String content, String path) {FileOutputStream fos = null;BufferedWriter bw = null;try {File file = new File(path);fos = new FileOutputStream(file);bw = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"));bw.write(content);} catch (FileNotFoundException fnfe) {fnfe.printStackTrace();} catch (IOException ioe) {ioe.printStackTrace();} finally {try {if (bw != null)bw.close();if (fos != null)fos.close();} catch (IOException ie) {}}}
}

3. 测试

@Test
public void testWord2Html() throws Exception{Word2HtmlUtil.word2Html("D:/test/doctest.doc", "D:/test/output/","doctest.html");
}

方案二:使用第三方服务

一般是收费的,一般也会提供功能受限的免费版本。

  • 永中 http://www.yozodcs.com/index.html (有免费版)
  • Office Web 365 http://www.officeweb365.com/ (有免费版)
  • I Doc View http://www.officeweb365.com/

方案三:使用微软 Office Online 服务

地址:https://products.office.com/zh-CN/office-online/view-office-documents-online

使用:在https://view.officeapps.live.com/op/view.aspx?src=后连接在线文档URL(必须为 http:// 或 https:// 形式,文档必须是 Word、Excel 或 PowerPoint 文档)。
测试:https://view.officeapps.live.com/op/view.aspx?src=http%3A%2F%2Fwww.snpdp.com%2Ffile-download-1064.html

163邮箱附件预览(高清版)就是使用office apps实现的:


永中文档预览服务详解

163邮箱附件预览(极速版)就是使用永中的服务实现的:

说明:
1.使用该方法,文档应该会被上传到永中的服务器,非公开文档不宜使用(购买的话应该也可以部署的自己的服务器上,不深究)。
2.下面测试方法中上传的文档不知道会不会被定时清理而不可用,不过如果有这个问题,只要申请免费受限账号应该就可以了。

1. 试一试在线预览!

地址:http://www.yozodcs.com/page/example.html
测试:http://www.yozodcs.com:8000/2019/04/11/MTkwNDExNTgxODc5MDUx.html

2. Web调用

(1)URL文档

$.ajax({url: "http://dcs.yozosoft.com:80/onlinefile", //服务地址data: {downloadUrl: "http://www.snpdp.com/file-download-1064.html", //要预览的文档地址convertType: "0"},dataType: "json",type: "post",success: function(data) {console.log(data);//window.location=data.data[0];},error: function(data) {console.error(data)}
});

接口说明、convertType参数取值说明、返回参数说明:http://www.yozodcs.com/help.html#link14

(2)上传文档
引入ajaxfileupload.js(jQuery-File-Upload)

<input id="fileupload" type="file" name="file"><!-- name值需为file,与永中接口参数名对应 --><script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="js/jquery.ui.widget.js"></script>
<script src="js/jquery.fileupload.js"></script><script>
$(function() {$('#fileupload').fileupload({url: 'http://dcs.yozosoft.com:80/upload',dataType: 'json',formData: {convertType: "0"},done: function(e, data) {console.log(data.result);}});
});
</script>

测试:http://dcs.yozosoft.com:8000/2019/04/12/MTkwNDEyNDAyNDM2MzMx.html

3. Java调用

(1)添加依赖

<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId><version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId><version>4.4.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpmime</artifactId><version>4.5.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.55</version>
</dependency>

(2)编写工具类DCSUtil.java

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;/**
* @Description: DCS文档转换服务Java调用代码示例
*/
public class DCSUtil {/*** 向指定 URL 发送POST方法的请求* @param url 发送请求的 URL* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。* @return 所代表远程资源的响应结果*/public static String sendPost(String url, String param) {PrintWriter out = null;BufferedReader in = null;String result = "";try {URL realUrl = new URL(url);// 打开和URL之间的连接URLConnection conn = realUrl.openConnection();conn.setRequestProperty("Accept-Charset", "UTF-8");// 设置通用的请求属性conn.setRequestProperty("accept", "*/*");conn.setRequestProperty("connection", "Keep-Alive");conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");// 发送POST请求必须设置如下两行conn.setDoOutput(true);conn.setDoInput(true);// 获取URLConnection对象对应的输出流out = new PrintWriter(conn.getOutputStream());// 发送请求参数out.print(param);// flush输出流的缓冲out.flush();// 定义BufferedReader输入流来读取URL的响应in = new BufferedReader(new InputStreamReader(conn.getInputStream()));String line;while ((line = in.readLine()) != null) {result += line;}} catch (Exception e) {System.out.println("发送 POST 请求出现异常!" + e);e.printStackTrace();}// 使用finally块来关闭输出流、输入流finally {try {if (out != null) {out.close();}if (in != null) {in.close();}} catch (IOException ex) {ex.printStackTrace();}}return result;}/*** 向指定 URL 上传文件POST方法的请求** @param url      发送请求的 URL* @param filepath 文件路径* @param type     转换类型* @return 所代表远程资源的响应结果, json数据*/public static String SubmitPost(String url, String filepath, String type) {String requestJson = "";HttpClient httpclient = new DefaultHttpClient();try {HttpPost httppost = new HttpPost(url);FileBody file = new FileBody(new File(filepath));MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,Charset.forName("UTF-8"));reqEntity.addPart("file", file); // file为请求后台的File upload;属性reqEntity.addPart("convertType", new StringBody(type, Charset.forName("UTF-8")));httppost.setEntity(reqEntity);HttpResponse response = httpclient.execute(httppost);int statusCode = response.getStatusLine().getStatusCode();if (statusCode == HttpStatus.SC_OK) {HttpEntity resEntity = response.getEntity();requestJson = EntityUtils.toString(resEntity);EntityUtils.consume(resEntity);}} catch (ParseException e) {// TODO Auto-generated catch blocke.printStackTrace();// requestJson = e.toString();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();// requestJson = e.toString();} finally {try {httpclient.getConnectionManager().shutdown();} catch (Exception ignore) {}}return requestJson;}
}

(3)测试

@Test
public void testDCS() {// 文件上传转换String convertByFile = DCSUtil.SubmitPost("http://dcs.yozosoft.com:80/upload", "D:/test/doctest.doc", "0");System.out.println(convertByFile);// 输出:{"result":0,"data":["http://dcs.yozosoft.com:8000/2019/04/12/MTkwNDEyNTM5NTE2Njk5.html"],"message":"转换成功","type":0}// 网络地址转换String convertByUrl = DCSUtil.sendPost("http://dcs.yozosoft.com:80/onlinefile","downloadUrl=http://www.snpdp.com/file-download-1064.html&convertType=1");System.out.println(convertByUrl);// 输出:{"result":0,"data":["http://dcs.yozosoft.com:8000/2019/04/12/MTkwNDEyNTQ0NjcyMDI3.html"],"message":"转换成功","type":1}
}

Office文档在线预览相关推荐

  1. Office文档在线预览接口服务器

    现在的Office文档在线预览基本都是收费的,但这个功能几乎在所有软件系统中都会有这个需求,微软有一个Office online是免费的,但是安装跟配置非常复杂,可以说用难度5颗星来形容,有没有一个更 ...

  2. office文档在线预览工具平台选型

    ​​​​​​在线预览原理 文档在线预览说明: 1.业务系统生成文档浏览地址,用户通过终端进行访 2.用户终端访问文档预览资源地址,请求文档解析器,解析器分为私有云和公有云部署,作用是将文档进行解析成x ...

  3. office 文档 在线预览功能实现(word,excel,pdf,ppt等多种格式)——使用https://view.xdocin.com/view 提示文档过期——基础积累

    web实现office文档在线预览功能--基础积累 最近遇到一个需求,就是要实现多种文档链接的在线预览,最简单的方式就是通过window.open(url地址)的方式来实现. 但是如果要求是在一个弹窗 ...

  4. office web viewer实现office文档在线预览

    office web viewer实现office文档在线预览 office web viewer官网介绍 若要自行制作 URL,您可使用以下链接,其中 <文档位置> 是文档的 URL. ...

  5. Office 文档在线预览

    现在的Office文档在线预览基本都是收费的,但这个功能几乎在所有软件系统中都会有这个需求,微软有一个Office online是免费的,但是安装跟配置非常复杂,可以说用难度5颗星来形容,有没有一个更 ...

  6. office 文档在线预览新姿势之永中云转换

    你知道的越多,你不知道的越多 点赞再看,养成习惯 如果您有疑问或者见解,或者需要毕业设计,大作业指导,购买付费源码等,欢迎指教: 企鹅:869192208 文章目录 前言: 一.接入准备 二.预览 w ...

  7. Office文档在线预览/在线编辑解决方案 - 毕升OfficeAPI说明

    毕升OfficeAPI说明 毕升OfficeAPI集成.onlyoffice api集成 使用毕升Office编辑,预览文件的过程 Api 具体说明 HMAC-MD5签名 callURL返回值 如何检 ...

  8. office文档 在线预览 (doc、ppt、xls)

    office 在线预览  调用微软的api,将office文档转换为html,然后实现预览. 参考我们的实现方式:http://demo.kalcaddle.com/?user/loginSubmit ...

  9. Office 文档在线预览解决方案

    目录 一.前言 二.解决方案 1.方案一:使用开源项目搭建私服 2.方案二:永中云转换 3.方案三:XDOC 4.方案四:Office Web 365 三.总结 一.前言 对于 offic 文档,在电 ...

最新文章

  1. c++STL(标准模板库)理论基础
  2. java cpu过高排查_论线上如何排查一次CPU100%的情况
  3. Kubernetes之yaml文件详解(汇总-详细)
  4. 使用nodejs创建Marketing Cloud的contact数据
  5. C# xml文件的创建,修改和添加节点 。
  6. .net显示今天农历的代码
  7. 如何在linux下通过ssh运行X图形软件
  8. 简述python程序的运行原理_谈谈 Python 程序的运行原理
  9. 如何在weblogic启动时让其加载指定的jar库文件
  10. 递归求出第n项斐波那契数列_Java
  11. centos7 安装pip
  12. Razor语法(四)
  13. (转)区别不同浏览器,CSS hack写法
  14. VS2017编译SNMP库
  15. 地图,GPS位置地图坐标系:WGS-84(GPS)、GCJ-02(Google地图)、BD-09(百度地图),OpenGIS
  16. 新浪短网址在线生成,官方api接口获取方案
  17. 台式u盘显示计算机未响应怎么办,u盘插上去电脑没反应怎么办_u盘插上后无任何反应的解决教程-系统城...
  18. 【等级测评师】等级测评师怎么报名?多少分及格?
  19. 【AVL树】AVL树的插入操作以及旋转
  20. PMI-ACP练习题(18)

热门文章

  1. 微软 Office for macOS 中文版正式版办公软件
  2. 怎样在外网登录访问CRM管理系统?
  3. Android N的Audio系统(五)
  4. 使用python pandas读取csv文件数据
  5. 分布式ID的生成方案
  6. 福建计算机等级考试分值,福建省考行测分值分布
  7. EXCEL通过多条件查询值
  8. js延迟加载的六种方式
  9. 怎样快速将pdf转excel转换
  10. 浅谈tcp cubic拥塞算法以及优化建议