doc 和 docx 略有不同,对于doc,可以用下面这种方式:
HWPFDocument wordDocument = new HWPFDocument(is);
WordToHtmlConverter converter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
//对HWPFDocument进行转换
converter.setPicturesManager(new PicturesManager() {
@Override
public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {
String type = pictureType.name();
return "data:image/" + type + ";base64," + new String(Base64.encodeBase64(content));
}
});
converter.processDocument(wordDocument);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
//是否添加空格
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "html");
transformer.transform(
new DOMSource(converter.getDocument()),
new StreamResult(response.getWriter()));
response.getWriter().flush();
wordDocument.close();
需要导入以下的类:
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.PictureType;
由于我做的是doc转HTML在线预览,所以为了方便图片都转成了base64编码。
下面是docx的情况:
XWPFDocument document = new XWPFDocument(is);
List<XWPFPictureData> list = document.getAllPictures();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
XHTMLConverter.getInstance().convert(document, outputStream, null);
String s = new String(outputStream.toByteArray());
s = setImg(s, list);
response.getWriter().write(s);
response.getWriter().flush();
document.close();
这个需要另外的setImg方法来修改生成的HTML,使用jsoup解析:
private String setImg(String html, List<XWPFPictureData> list){
Document doc = Jsoup.parse(html);
Elements elements = doc.getElementsByTag("img");
if (elements != null && elements.size() > 0 && list != null){
for(Element element : elements){
String src = element.attr("src");
for (XWPFPictureData data: list){
if (src.contains(data.getFileName())){
String type = src.substring(src.lastIndexOf(".") + 1);
String base64 = "data:image/" + type + ";base64," + new String(Base64.encodeBase64(data.getData()));
element.attr("src", base64);
break;
}
}
}
}
return doc.toString();
}
需要导入:
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
以上