记录下利用poi 将word文件转为html文件,兼容doc及docx。
本地main方法运行成功,用到的jar包包括:
关于jar:之前在网上搜索的内容,未找到具体jar的版本,于是随意下的版本,出现了nosuchmethod或者ClassNoDefException异常,就是说白了jar冲突。。。然后在maven库http://mvnrepository.com/search?q=pdf上把所有的2015年的这几个jar下载了,我猜测同一年的应该不会有jar冲突。(xmlbeans不是2015的)。
代码大致如下:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.io.output.ByteArrayOutputStream;
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.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.IURIResolver;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;
public class PoiUtil {
public static void main(String[] args) {
try {
wordToHtml("d:\\12345.docx", "d:\\", "123456.html");
wordToHtml("d:\\123.doc", "d:\\", "123.html");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void wordToHtml(String wordPath, String htmlPath,
String newFilename) throws Exception {
convert2Html(wordPath, htmlPath, newFilename);
}
public static void writeFile(String content, String path) {
FileOutputStream fos = null;
BufferedWriter bw = null;
try {
File file = new File(path);
fos = new FileOutputStream(file);
bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(content);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fos != null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* word转html,支持doc docx
* @param fileName word文件名
* @param outPutFilePath html存储路径
* @param newFileName html名
* @throws Exception
*/
public static void convert2Html(String fileName, String outPutFilePath,
String newFileName) throws Exception {
String substring = fileName.substring(fileName.lastIndexOf(".") + 1);
ByteArrayOutputStream out = new ByteArrayOutputStream();
/**
* word2007和word2003的构建方式不同, 前者的构建方式是xml,后者的构建方式是dom树。
* 文件的后缀也不同,前者后缀为.docx,后者后缀为.doc 相应的,apache.poi提供了不同的实现类。
*/
if ("docx".equals(substring)) {
InputStream inputStream = new FileInputStream(new File(fileName));
XWPFDocument document = new XWPFDocument(inputStream);
final String imageUrl = "";
XHTMLOptions options = XHTMLOptions.create();
options.setExtractor(new FileImageExtractor(new File(outPutFilePath
+ imageUrl)));
options.setIgnoreStylesIfUnused(false);
options.setFragment(true);
options.URIResolver(new IURIResolver() {
@Override
public String resolve(String uri) {
return imageUrl + uri;
}
});
XHTMLConverter.getInstance().convert(document, out, options);
} else {
HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(
fileName));
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
DocumentBuilderFactory.newInstance().newDocumentBuilder()
.newDocument());
wordToHtmlConverter.setPicturesManager(new PicturesManager() {
public String savePicture(byte[] content,
PictureType pictureType, String suggestedName,
float widthInches, float heightInches) {
return suggestedName;
}
});
wordToHtmlConverter.processDocument(wordDocument);
List pics = wordDocument.getPicturesTable().getAllPictures();
if (pics != null) {
for (int i = 0; i < pics.size(); i++) {
Picture pic = (Picture) pics.get(i);
try {
pic.writeImageContent(new FileOutputStream(
outPutFilePath + pic.suggestFullFileName()));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Document htmlDocument = wordToHtmlConverter.getDocument();
DOMSource domSource = new DOMSource(htmlDocument);
StreamResult streamResult = new StreamResult(out);
TransformerFactory tf = TransformerFactory.newInstance(); // 这个应该是转换成xml的
Transformer serializer = tf.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.METHOD, "html");
serializer.transform(domSource, streamResult);
}
out.close();
writeFile(new String(out.toByteArray()), outPutFilePath + newFileName);
}
}