1

我有一些代码使用 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;

}
4

3 回答 3

3

查看http://svn.apache.org/viewvc/poi/trunk/src/scratchpad/src/org/apache/poi/hwpf/converter/WordToHtmlConverter.java?view=markup&pathrev=1180740org.apache.poi.hwpf.converter.WordToHtmlConverter的 源代码JavaDoc 中的状态:



此实现不会创建图像或指向它们的链接。这可以通过覆盖 {@link #processImage(Element, boolean, Picture)} 方法来改变

如果您processImage(...)在第 790 行查看 AbstractWordConverter.java 中的该方法,看起来该方法正在调用另一个名为processImageWithoutPicturesManager(...).

http://svn.apache.org/viewvc/poi/trunk/src/scratchpad/src/org/apache/poi/hwpf/converter/AbstractWordConverter.java?view=markup&pathrev=1180740

这个方法又被定义WordToHtmlConverter了,看起来很可疑就像您想要扩展代码的地方一样(第 317 行):

@Override
protected void processImageWithoutPicturesManager(Element currentBlock,
    boolean inlined, Picture picture)
{
    // no default implementation -- skip
    currentBlock.appendChild(htmlDocumentFacade.document
    .createComment("Image link to '"
    + picture.suggestFullFileName() + "' can be here"));
}

我认为你有开始将图像插入流程的地方。

创建转换器的子类,例如

    public class InlineImageWordToHtmlConverter extends WordToHtmlConverter

然后覆盖该方法并将任何代码放入其中。

我还没有测试过,但从我理论上看它应该是正确的方法。

于 2012-10-31T16:18:08.837 回答
1

@user4887078 正如@Guga 所说,这很简单,我所做的只是查看 org.apache.poi.xwpf.converter.core.FileImageExtractor 和 瞧! 它确实可以按预期工作,尽管它可能仍需要一些重构和优化。

HWPFDocumentCore wordDocument = WordToHtmlUtils.loadDoc(is);

            WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
                    DocumentBuilderFactory.newInstance().newDocumentBuilder()
                            .newDocument());
            wordToHtmlConverter.setPicturesManager(new PicturesManager() {
                @Override
                public String savePicture(byte[] bytes, PictureType pictureType, String s, float v, float v1) {
                    File imageFile = new File("pages/imgs", s);
                    imageFile.getParentFile().mkdirs();
                    InputStream in = null;
                    FileOutputStream out = null;

                    try {
                        in = new ByteArrayInputStream(bytes);
                        out = new FileOutputStream(imageFile);
                        IOUtils.copy(in, out);

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (in != null) {
                            IOUtils.closeQuietly(in);
                        }

                        if (out != null) {
                            IOUtils.closeQuietly(out);
                        }

                    }
                    return "imgs/" + imageFile.getName();
                }
            });
            wordToHtmlConverter.processDocument(wordDocument);
            Document htmlDocument = wordToHtmlConverter.getDocument();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            DOMSource domSource = new DOMSource(htmlDocument);
            StreamResult streamResult = new StreamResult(out);


            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.METHOD, "html");
            transformer.transform(domSource, streamResult);
            out.close();

            String result = new String(out.toByteArray());
            FileOutputStream fos = new FileOutputStream(outFile);
于 2017-09-07T12:18:30.077 回答
0

使用这个应该很有用。

public class InlineImageWordToHtmlConverter extends WordToHtmlConverter{
    public InlineImageWordToHtmlConverter(Document document) {
        super(document);
    } 

    @Override
    protected void processImageWithoutPicturesManager(Element currentBlock, boolean inlined, Picture picture) {
        Element img = super.getDocument().createElement("img");
        img.setAttribute("src", "data:image/png;base64,"+Base64.getEncoder().encodeToString(picture.getContent()));
        currentBlock.appendChild(img);
    }
}
于 2017-12-22T01:42:56.243 回答