【发布时间】:2012-10-30 13:58:53
【问题描述】:
我有一些代码使用 Java Apache POI 库打开 Microsoft Word 文档并将其转换为 html,使用 Apache POI,它还获取文档上图像的字节数组数据。但我需要将此信息转换为 html 以写入 html 文件。任何提示或建议将不胜感激。请记住,我是一名桌面开发人员,而不是一名网络程序员,所以当你提出建议时,请记住这一点。下面的代码获取图像。
private void parseWordText(File file) throws IOException {
FileInputStream fs = new FileInputStream(file);
doc = new HWPFDocument(fs);
PicturesTable picTable = doc.getPicturesTable();
if (picTable != null){
picList = new ArrayList<Picture>(picTable.getAllPictures());
if (!picList.isEmpty()) {
for (Picture pic : picList) {
byte[] byteArray = pic.getContent();
pic.suggestFileExtension();
pic.suggestFullFileName();
pic.suggestPictureType();
pic.getStartOffset();
}
}
}
然后下面的代码将文档转换为 html。有没有办法在下面的代码中将 byteArray 添加到 ByteArrayOutputStream 中?
private void convertWordDoctoHTML(File file) throws ParserConfigurationException, TransformerConfigurationException, TransformerException, IOException {
HWPFDocumentCore wordDocument = null;
try {
wordDocument = WordToHtmlUtils.loadDoc(new FileInputStream(file));
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
wordToHtmlConverter.processDocument(wordDocument);
org.w3c.dom.Document htmlDocument = wordToHtmlConverter.getDocument();
NamedNodeMap node = htmlDocument.getAttributes();
ByteArrayOutputStream out = new ByteArrayOutputStream();
DOMSource domSource = new DOMSource(htmlDocument);
StreamResult streamResult = new StreamResult(out);
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);
out.close();
String result = new String(out.toByteArray());
acDocTextArea.setText(newDocText);
htmlText = result;
}
【问题讨论】:
-
看看这个例子,它使用 POI WordToHtmlConverter: stackoverflow.com/questions/7868713/…
-
我已经让那部分代码工作了,我正在询问如何将图片放入 html 中。你知道我在上面创建的图片列表。
-
所以您的意思是,您想将图片直接编码到您的文档的 HTML 标记中,而不做
<img src="http://..."/>引用?有一个适用于大多数现代浏览器的数据 URI,例如<img src="data:image/png;base64,..."/>。见en.wikipedia.org/wiki/Data_URI_scheme。 -
所以,Udo,我不是网络开发人员,我该怎么办?哪个更容易实现?
-
您是否考虑过使用 Apache Tika?这已经提供了一种封装 Apache POI 并输出 HTML 版本以及任何嵌入式资源(例如图像)的方法,因此您可以避免重新发明轮子!
标签: java html image ms-word apache-poi