用OpenOffice实现Word转Html完整方案

      网上比较流行的Word转Html有Jacob、POI和OpenOffice。

      在这里简单说下Jacob,Jacob是调用MS Office完成Word转Html,用到Jacob.jar和Jacob.dll。

      我试了下官方最新版的Jacob1.17版本,同一个word文件Jacob好是3S,转换的html在IE8下浏览正常,在IE11和Firefox下浏览有兼容性问题;OpenOffice耗时1.5S,主流浏览器没有兼容性问题。

      OpenOffice转换html后会有文档内容靠页面左对齐的问题,这里页面样式代码改下就可以了,样式转换后对齐方式和Word文档对齐方式一致,图片居中显示。

public class JodUtils {
	
	/**
	 * jod转换类
	 * @param File source	office文件    
	 * @param File html		转换输出html文件 
	 * @throws IOException
	 */
	public static void converter(File source, File html) throws IOException {
		OpenOfficeConnection con = new SocketOpenOfficeConnection(8100);  
        try {  
            con.connect();  
        } catch (ConnectException e) {  
            System.err.println("文件转换出错,请检查OpenOffice服务是否启动。");  
            e.printStackTrace();  
        }  
        DocumentConverter converter = new OpenOfficeDocumentConverter(con);  
        converter.convert(source, html);  
        con.disconnect();
        
        formatStyle(html);
	}
	
	/**
	 * html样式转换
	 * @param File html	html文件          
	 */
	public static void formatStyle(File html) {
		String file_path = null;
		StringBuffer s_html = new StringBuffer();
		
		try {
			//读取文件路径   
			file_path = html.getPath();
			
			//读取文件 
	        BufferedReader br = new BufferedReader(new InputStreamReader(
	            new FileInputStream(html), "GBK"));
	        while (br.ready()) {
	        	s_html.append(br.readLine());
	        }
	        br.close();
	        // 删除临时文件
	        html.delete();
	        
	        //写文件
	        BufferedWriter writer = null;
	        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(file_path)),"GBK")); 
	        writer.write(formatStyleUtils(s_html.toString()));
	        writer.close();
	    } catch (FileNotFoundException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	}
	
	/**
	 * html样式转换工具
	 * @param String html	html代码
	 * @return
	 */
	public static String formatStyleUtils(String html) {
		
		//去除左对齐样式
		//P { margin-bottom: 0.21cm; direction: ltr; color: #000000; /**text-align: justify;**/ widows: 0; orphans: 0 }
		html = html.replaceFirst("text-align: justify;", "");
		
		//图片居中样式
		html = html.replaceAll("<IMG", "<CENTER><IMG");
		
		return html;
	}
	
}

 

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

      

      java OpenOffice把word转html(Convert word to html

      

      去掉word冗余格式 java正则表达式

猜你喜欢

转载自76581349.iteye.com/blog/2070041