public classDocToHtml {private static final String encoding = "UTF-8";public staticString convert2Html(String wordPath)throwsFileNotFoundException, TransformerException, IOException,
ParserConfigurationException {if( wordPath == null || "".equals(wordPath) ) return "";
File file= newFile(wordPath);if( file.exists() &&file.isFile() )return convert2Html(newFileInputStream(file));else
return "";
}public staticString convert2Html(String wordPath, String context)throwsFileNotFoundException, TransformerException, IOException,
ParserConfigurationException {if( wordPath == null || "".equals(wordPath) ) return "";
File file= newFile(wordPath);if( file.exists() &&file.isFile() )return convert2Html(newFileInputStream(file), context);else
return "";
}public staticString convert2Html(InputStream is)throwsTransformerException, IOException,
ParserConfigurationException {return convert2Html(is, "");
}public static String convert2Html(InputStream is, HttpServletRequest req) throwsTransformerException, IOException, ParserConfigurationException {returnconvert2Html(is, req.getContextPath());
}public static String convert2Html(InputStream is, final String context) throwsIOException, ParserConfigurationException, TransformerException {
HWPFDocument wordDocument= newHWPFDocument(is);
WordToHtmlConverter converter= newWordToHtmlConverter(
DocumentBuilderFactory.newInstance().newDocumentBuilder()
.newDocument());
SimpleDateFormat sdf= new SimpleDateFormat("yyyyMMddHHmmssSSS");final String prefix = sdf.format(newDate());final Map suffixMap = new HashMap();
converter.setPicturesManager(newPicturesManager() {public String savePicture(byte[] content, PictureType pictureType,
String suggestedName,float widthInches, floatheightInches) {
String prefixContext= context.replace("\\", "").replace("/", "");
prefixContext= StringUtils.isNotBlank(prefixContext) ? "/" + prefixContext + "/": prefixContext;
suffixMap.put(new String(content).replace(" ", "").length(), suggestedName);returnprefixContext+ UeConstants.VIEW_IMAGE_PATH + "/" +UeConstants.UEDITOR_PATH+ "/" + UeConstants.UEDITOR_IMAGE_PATH + "/"
+ prefix + "_"
+suggestedName;
}
});
converter.processDocument(wordDocument);
List pics =wordDocument.getPicturesTable().getAllPictures();if (pics != null) {for(Picture pic : pics) {try{
pic.writeImageContent(newFileOutputStream(
UeConstants.IMAGE_PATH+ "/" + prefix + "_" + suffixMap.get(new String(pic.getContent()).replace(" ", "").length())));
}catch(FileNotFoundException e) {
e.printStackTrace();
}
}
}
StringWriter writer= newStringWriter();
Transformer serializer=TransformerFactory.newInstance().newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, encoding);
serializer.setOutputProperty(OutputKeys.INDENT,"yes");
serializer.setOutputProperty(OutputKeys.METHOD,"html");
serializer.transform(newDOMSource(converter.getDocument()),newStreamResult(writer) );
writer.close();returnwriter.toString();
}
}