为什么会想起来将上传的word文档转换成html格式呢?设想,如果一个系统需要发布在页面的文章都是来自word文档,一般会执行下面的流程:使用word打开文档,Ctrl+A,进入发布文章页面,Ctrl+V。看起来也不麻烦,但是,如果文档中包含大量图片呢?尴尬的事是图片都需要重新上传吧?

如果可以将已经编写好的word文档上传到服务器就可以在相应页面进行展示,将会是一件非常惬意的事情,最起码信息发布人员会很开心。程序员可能就不会这么想了,囧。

将Word转Html的原理是这样的:

1、客户上传Word文档到服务器

2、服务器调用OpenOffice程序打开上传的Word文档

3、OpenOffice将Word文档另存为Html格式

4、Over

至此可见,这要求服务器端安装OpenOffice软件,其实也可以是MS Office,不过OpenOffice的优势是跨平台,你懂的。恩,说明一下,本文的测试基于 MS Win7 Ultimate X64 系统。

下面就是规规矩矩的实现。

1、下载OpenOffice,http://download.openoffice.org/index.html So easy...

2、下载Jodconverter http://www.artofsolving.com/opensource/jodconverter 这是一个开启OpenOffice进行格式转化的第三方jar包。

3、泡杯热茶,等待下载。

4、安装OpenOffice,安装结束后,调用cmd,启动OpenOffice的一项服务:C:\Program Files (x86)\OpenOffice.org 3\program>soffice -headless -accept="socket,port=8100;urp;"

5、打开eclipse

6、喝杯热茶,等待eclipse打开。

7、新建eclipse项目,导入Jodconverter/lib 下得jar包。

8、Coding...

package com.mzule.doc2html.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.util.Date;
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; /**
* 将Word文档转换成html字符串的工具类
*
* @author MZULE
*
*/
public class Doc2Html { public static void main(String[] args) {
System.out
.println(toHtmlString(new File("C:/test/test.doc"), "C:/test"));
} /**
* 将word文档转换成html文档
*
* @param docFile
* 需要转换的word文档
* @param filepath
* 转换之后html的存放路径
* @return 转换之后的html文件
*/
public static File convert(File docFile, String filepath) {
// 创建保存html的文件
File htmlFile = new File(filepath + "/" + new Date().getTime()
+ ".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);
// 获取html文件流
StringBuffer htmlSb = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(htmlFile)));
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();
// 返回经过清洁的html文本
return clearFormat(htmlStr, filepath);
} /**
* 清除一些不需要的html标记
*
* @param htmlStr
* 带有复杂html标记的html语句
* @return 去除了不需要html标记的语句
*/
protected 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=\"" + docImgPath
+ "/");
// 把<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;
} }
package com.mzule.doc2html.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.util.Date;
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; /**
* 将Word文档转换成html字符串的工具类
*
* @author MZULE
*
*/
public class Doc2Html { public static void main(String[] args) {
System.out
.println(toHtmlString(new File("C:/test/test.doc"), "C:/test"));
} /**
* 将word文档转换成html文档
*
* @param docFile
* 需要转换的word文档
* @param filepath
* 转换之后html的存放路径
* @return 转换之后的html文件
*/
public static File convert(File docFile, String filepath) {
// 创建保存html的文件
File htmlFile = new File(filepath + "/" + new Date().getTime()
+ ".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);
// 获取html文件流
StringBuffer htmlSb = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(htmlFile)));
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();
// 返回经过清洁的html文本
return clearFormat(htmlStr, filepath);
} /**
* 清除一些不需要的html标记
*
* @param htmlStr
* 带有复杂html标记的html语句
* @return 去除了不需要html标记的语句
*/
protected 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=\"" + docImgPath
+ "/");
// 把<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;
} }

类组织的不好,博友凑合看,代码注释比较详细了,不多说。

两个公开的方法是独立使用的,toHtmlString(...)方法是转化文件并获取html代码,以备存入数据库。

参考了http://dangry.iteye.com/blog/858787,表示感谢。

OpenOffice Word文档转换成Html格式的更多相关文章

  1. JAVA:借用OpenOffice将上传的Word文档转换成Html格式

    为什么会想起来将上传的word文档转换成html格式呢?设想,如果一个系统需要发布在页面的文章都是来自word文档,一般会执行下面的流程:使用word打开文档,Ctrl+A,进入发布文章页面,Ctrl ...

  2. C# word文档转换成PDF格式文档

    最近用到一个功能word转pdf,有个方法不错,挺方便的,直接调用即可,记录下 方法:ConvertWordToPdf(string sourcePath, string targetPath) so ...

  3. java将XML文档转换成json格式数据

    功能 将xml文档转换成json格式数据 说明 依赖包:1. jdom-2.0.2.jar : xml解析工具包;2. fastjson-1.1.36.jar : 阿里巴巴研发的高性能json工具包 ...

  4. 将html版API文档转换成chm格式的API文档

    文章完全转载自: https://blog.csdn.net/u012557538/article/details/42089277 将html版API文档转换成chm格式的API文档并不是一件难事, ...

  5. ASP.NET将word文档转换成pdf的代码

    一.添加引用 using Microsoft.Office.Interop.Word; 二.转换方法 1.方法 C# 代码 /// <summary> /// 把Word文件转换成pdf文 ...

  6. poi解析word文档转换成html(包括图片解析)

    需求:将本地上传的word文档解析并放入数据库中 代码: import java.io.ByteArrayOutputStream;import java.io.File;import java.io ...

  7. Python将word文档转换成PDF文件

    如题. 代码: ''' #將word文档转换为pdf文件 #用到的库是pywin32 #思路上是调用了windows和office功能 ''' #导入所需库 from win32com.client ...

  8. Java利用aspose-words将word文档转换成pdf(破解 无水印)

    首先下载aspose-words-15.8.0-jdk16.jar包 http://pan.baidu.com/s/1nvbJwnv 引入jar包,编写Java代码 package doc; impo ...

  9. 如何用C#把Doc文档转换成rtf格式

    先在项目引用里添加上对Microsoft Word 9.0 object library的引用 using System; namespace DocConvert { class DoctoRtf ...

随机推荐

  1. 杂项-ORM:LinqToSQL

    ylbtech-杂项-ORM:LinqToSQL LINQ TO SQL 是包含在.NET Framework 3.5 版中的一种 O/RM 组件(对象关系映射),O/RM 允许你使用 .NET 的类 ...

  2. 杂项:ORM

    ylbtech-杂项:ORM 对象关系映射(英语:(Object Relational Mapping,简称ORM,或O/RM,或O/R mapping),是一种程序技术,用于实现面向对象编程语言里不 ...

  3. win7连接centos的nfs

    nfs的服务端这边设置忽略. 主要关于权限的问题: Windows7 NFS客户端,使用mount命令挂载NFS服务之后,文件系统对Win7只读,无法写入文件,无法新建文件夹解决方法. 在win的cm ...

  4. [UE4]场景光照改进PostProcessVolume

    PostProcessVolume可以做的效果很多,其中就可以实现太阳光斑效果. Unbound勾上上,就表示不受“PostProcessVolume”组件的大小限制,直接应用到整个世界.如果不勾选, ...

  5. javascript创建对象之动态原型模式(五)

    function Human(name, sex) { this.name = name; this.sex = sex; if (typeof this.say != "function& ...

  6. javascript创建对象之函数构造模式和原型模式结合使用(四)

    创建自定义类型的常见方式就是组合使用构造函数模式与原型模式一起使用. 构造函数模式用于定义实例对象的特有的部分(属性和方法),原型模式用于定义共享的部分. 这样最大限度的节省了内存的开销. funct ...

  7. spring的Ioc容器与AOP机制

    为什么要使用Spring的Ioc容器? 1.首先,spring是一个框架,框架存在的目的就是给我们的编程提供简洁的接口,可以使得我们专注于业务的开发,模块化,代码简洁,修改方便. 通过使用spring ...

  8. Windows10 命令行中使用网络驱动器

    Windows10中,我们在局域网内使用共享文件夹,建立映射的网络驱动器,有时候需要一些软件去调用网络驱动器内的资源,但是发现在资源管理器能正常打开,应用软件却无法识别,命令行中提示:“系统找不到指定 ...

  9. for /f命令之—Delims和Tokens用法&总结

    在For命令语踞饽参数F中,最难理解的就是Delims和Tokens两个选项,本文简单的做一个比较和总拮.“For /f”常用来解析文本,读取字符串.分工上,delims负责切分字符串,而tokens ...

  10. 《opencv学习》 之 OTSU算法实现二值化

    主要讲解OTSU算法实现图像二值化:    1.统计灰度级图像中每个像素值的个数. 2.计算第一步个数占整个图像的比例. 3.计算每个阈值[0-255]条件下,背景和前景所包含像素值总个数和总概率(就 ...