我需要将 .docx 文件内容转换为 HTML 文本以便在 web ui 中显示。
我使用了Apache POI的XWPFDocument类,但还没有得到任何结果;得到空字符串。我的代码基于此示例。
这也是我的代码:
public JSONObject uploadDocxFile(MultipartFile multipartFile) throws Exception {
InputStream inputStream = multipartFile.getInputStream();
XWPFDocument wordDocument = new XWPFDocument(inputStream);
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
org.w3c.dom.Document htmlDocument = wordToHtmlConverter.getDocument();
ByteArrayOutputStream out = new ByteArrayOutputStream();
DOMSource domSource = new DOMSource(htmlDocument);
StringWriter stringWriter = new StringWriter();
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, new StreamResult(stringWriter));
out.close();
String result = new String(out.toByteArray());
String htmlText = result;
JSONObject jsonObject = new JSONObject();
jsonObject.put("content", htmlText);
jsonObject.put("success", true);
return jsonObject;
}