1. 需求
上传 word 之后 ,有时候会需要预览 上传的 word ,这个时候可以把 word 转为 html 然后在页面显示
2.测试 jar 包
gradle 依赖 (文件处理相关 jar 包)
compile group: 'org.apache.poi', name: 'poi', version: '3.13'//word excel 解析
compile group: 'org.apache.poi', name: 'poi-ooxml', version: '3.13'//word excel 解析
compile group: 'org.apache.poi', name: 'poi-scratchpad', version: '3.13'//word excel 解析
compile group: 'fr.opensagres.xdocreport', name: 'org.apache.poi.xwpf.converter.xhtml', version: '1.0.6'//docx 解析为 html
compile group: 'org.jsoup', name: 'jsoup', version: '1.10.1'//html 解析
3. 代码案例
util 类
package com.ycit.utils;
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.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.jsoup.Jsoup;
import org.springframework.util.CollectionUtils;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
/**
* Created by xlch on 2017/1/11.
*/
public class POIUtils {
public static String docToHtml(HWPFDocument document, String path) throws Exception {
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
wordToHtmlConverter.setPicturesManager(new PicturesManager() {
@Override
public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {
return suggestedName;
}
});
wordToHtmlConverter.processDocument(document);
List<Picture> pictures = document.getPicturesTable().getAllPictures();
if (!CollectionUtils.isEmpty(pictures)) {
for (Picture picture:pictures) {
picture.writeImageContent(new FileOutputStream(path + picture.suggestFullFileName()));
}
}
Document htmlDocument = wordToHtmlConverter.getDocument();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
DOMSource domSource = new DOMSource(htmlDocument);
StreamResult streamResult = new StreamResult(outStream);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.METHOD, "html");
serializer.transform(domSource, streamResult);
outStream.close();
return new String(outStream.toByteArray(), "utf-8");
}
/**
* 处理表格会有点问题
* @param document
* @param path
* @return
* @throws IOException
*/
public static String docXToHtml(XWPFDocument document, String path)throws IOException {
XHTMLOptions options = XHTMLOptions.create();
options.setIgnoreStylesIfUnused(false);
options.setFragment(true);
options.setExtractor(new FileImageExtractor(new File(path)));
ByteArrayOutputStream out = new ByteArrayOutputStream();
XHTMLConverter.getInstance().convert(document, out, options);
String content = new String(out.toByteArray());
org.jsoup.nodes.Document document1 = Jsoup.parse(content);
return document1.html();
}
}
若保存为 html 文件 则
将
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
该为
OutputStream outputStream = new FileOutputStream(new File("你的存储路径"));
测试类:
package com.ycit.poi;
import com.ycit.utils.POIUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
/**
* Created by xlch on 2016/12/30.
*/
public class WordToHtml {
@Test
public void wordToHtml() throws Exception {
String path = "D:\\about project\\perp-service\\5812-1.doc";
// String path = "D:\\about project\\perp-service\\11.docx";
File file = new File(path);
String content;
String paths = "D:\\about project\\perp-service\\";
FileInputStream in = new FileInputStream(file);
if (".docx".equals(path.substring(path.lastIndexOf(".", path.length())))) {
XWPFDocument document = new XWPFDocument(in);
content = POIUtils.docXToHtml(document,paths);
} else if (".doc".equals(path.substring(path.lastIndexOf(".", path.length())))) {
HWPFDocument document = new HWPFDocument(in);
content = POIUtils.docToHtml(document,paths);
} else {
throw new RuntimeException("文件格式不正确");
}
System.out.println(content);
}
}