关于DOC转HTML的初始代码详见:
http://chembo.iteye.com/blog/1510536
在这部分代码即有
wordToHtmlConverter.setPicturesManager()
也通过
wordDocument.getPicturesTable().getAllPictures()
将Document的Pictures保存到硬盘
但实际操作过程中会发现这两个方法得到的Pictures数量是不一致的,后部分代码不包含通过Doc绘制的图片,而前面部分代码能获得这部分图片,于是将这部分代码改造
converter.setPicturesManager(new PicturesManager() {
public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {
try {
FileOutputStream fos=new FileOutputStream(path + suggestedName);
fos.write(content);
} catch (Exception e) {
e.printStackTrace();
}
return suggestedName;
}
});
去掉
wordDocument.getPicturesTable().getAllPictures()
这部分代码。
这样改造能解决图片不一致的问题,却发现另外一个问题,在转成html的时候word中正常的图片能在网页中显示正常的高度和宽度,但是针对通过Doc绘制的图片,img标签是没有高度和宽度的。会发现在html中呈现原始大小与word不保持一致。
通过阅读WordToHtmlConverter源代码发现:
protected void processDrawnObject(HWPFDocument doc,
CharacterRun characterRun, OfficeDrawing officeDrawing,
String path, Element block) {
/* 302*/Element img = htmlDocumentFacade.createImage(path);
/* 303*/block.appendChild(img);
}
这段代码只在html中生成了img标签而没有设置它的高度和宽度。
于是将这个方法改造一下:
protected void processDrawnObject( HWPFDocument doc,
CharacterRun characterRun, OfficeDrawing officeDrawing,
String path, Element block )
{
Element img = htmlDocumentFacade.createImage( path );
float width = (float) (officeDrawing.getRectangleRight() - officeDrawing
.getRectangleLeft()) / 1440F;
float height = (float) (officeDrawing.getRectangleBottom() - officeDrawing
.getRectangleTop()) / 1440F;
img.setAttribute(
"style",
(new StringBuilder()).append("width:").append(width)
.append("in;height:").append(height)
.append("in;vertical-align:text-bottom;")
.toString());
block.appendChild( img );
}
大功告成。