main 方法 con.connect(); 能连接成功, 在javaweb 调用该工具类 报错
森_ 2016-11-29 08:41:05 /**
* 将word文档转换成html文档
*
* @param docFile
* 需要转换的word文档
* @param filepath
* 转换之后html的存放路径
* @return 转换之后的html文件
*/
public File convert(String docFile, String filepath,String openOffice,String openOfficeBat) throws IOException {
//创建源文件
File inputFile = new File(docFile);
// 创建保存html的文件
File htmlFile = new File(filepath);
// 创建Openoffice连接
// offices(openOffice,openOfficeBat);
OpenOfficeConnection con = new SocketOpenOfficeConnection("127.0.0.1",8100);
try {
// 连接
con.connect();
// 创建转换器
DocumentConverter converter = new OpenOfficeDocumentConverter(con);
// 转换文档问html
converter.convert(inputFile, htmlFile);
} catch (ConnectException e) {
e.printStackTrace();
}finally {
// 关闭openoffice连接
try{ if(con != null){con.disconnect(); con = null;}}catch(Exception e){}
}
//DistorySoffice();
return htmlFile;
}
/**
* 将word转换成html文件,并且获取html文件代码。
*
* @param docFile
* 需要转换的文档
* @param filepath
* 文档中图片的保存位置
* @return 转换成功的html代码
*/
public String toHtmlString(String docFile, String filepath, String preview, String openOffice, String openOfficeBat) throws IOException {
// 转换word文档
File htmlFile = convert(docFile, filepath,openOffice,openOfficeBat);
// 获取html文件流
StringBuffer htmlSb = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(htmlFile),"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();
// 返回经过清洁的html文本
return clearFormat(htmlStr, preview);
}
/**
* 清除一些不需要的html标记
*
* @param htmlStr
* 带有复杂html标记的html语句
* @return 去除了不需要html标记的语句
*/
public String clearFormat(String htmlStr, String preview) {
// 获取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=\"" + preview
+ "/");
// 把<P></P>转换成</div></div>保留样式
htmlStr = htmlStr.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;
}