Docx4J初体验2
在经过CSDN,stack overflow以及官网论坛的洗礼后。
简单的写出了两个demo。
这个是读取word中的文字,但是图片不能解析??
喵喵喵??
还需要继续观察一波。
/**
* 作者:苏晓峰
* 时间:2019年7月3日10:37:16
* 读取word中的文字不包含图片,不包含格式
*/
@Test
public void readParagraph() {
try {
WordprocessingMLPackage wordprocessingMLPackage = WordprocessingMLPackage
.load(new File("C:\\Users\\Administrator\\Desktop\\Test.docx"));
String contentType = wordprocessingMLPackage.getContentType();
System.out.println("contentType -> {}"+contentType);
MainDocumentPart mainDocumentPart = wordprocessingMLPackage.getMainDocumentPart();
List<Object> content = mainDocumentPart.getContent();
for (Object ob : content) {
System.out.println("ob -> {}"+ob);
}
} catch (Docx4JException e) {
System.err.println("createDocx error: Docx4JException"+e);
}
}
这个是读取word转换成html,但是样式乱掉??行内元素不知道怎么取消??
喵喵喵??
还需要继续观察一波。
/**
* 作者:苏晓峰
* 时间:2019年7月3日10:40:23
* 生成html文件,但是图片会有emf格式
* 且一些行内元素减少了数据的可读性
*/
@Test
public void docxToHtml() throws Docx4JException, FileNotFoundException {
String docxFilePath = "C:\\Users\\Administrator\\Desktop\\Test.docx";
String htmlPath = "C:\\Users\\Administrator\\Desktop\\test1.xhtml";
//加载word文件
WordprocessingMLPackage wordMLPackage= Docx4J.load(new java.io.File(docxFilePath));
//创建HTML 样式设置
HTMLSettings htmlSettings = Docx4J.createHTMLSettings();
//获取图片存储路径
String imageFilePath=htmlPath.substring(0,htmlPath.lastIndexOf("\\")+1)+"\\images";
//设置图片存储路径
htmlSettings.setImageDirPath(imageFilePath);
//设置图片的地址
htmlSettings.setImageTargetUri( "images");
//
htmlSettings.setWmlPackage(wordMLPackage);
String userCSS = "html, body, div, span, h1, h2, h3, h4, h5, h6, p, a, img, ol, ul, li, table, caption, tbody, tfoot, thead, tr, th, td " +
"{ margin: 2; padding: 2; border: 1;}" +
"body {line-height: 2;} ";
htmlSettings.setUserCSS(userCSS);
OutputStream os;
os = new FileOutputStream(htmlPath);
Docx4jProperties.setProperty("docx4j.Convert.Out.HTML.OutputMethodXML", true);
Docx4J.toHTML(htmlSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
}
继续深入观察,看看怎么实现。
有问题不要慌,官网论坛
stackoverflow
先走一波。
Q.E.D.