1

Java ApachePOIライブラリを使用してMicrosoftWordドキュメントを開き、Apache POIを使用してhtmlに変換するコードがあります。また、ドキュメント上の画像のバイト配列データも取得します。しかし、htmlファイルに書き出すには、この情報をhtmlに変換する必要があります。ヒントや提案をいただければ幸いです。私はデスクトップ開発者であり、Webプログラマーではないことを忘れないでください。提案を行うときは、それを覚えておいてください。以下のコードは画像を取得します。

 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=1180740Itのソースコードorg.apache.poi.hwpf.converter.WordToHtmlConverterを 見るJavaDocの状態:



この実装では、画像やそれらへのリンクは作成されません。これは、{@ link #processImage(Element、boolean、Picture)}メソッドをオーバーライドすることで変更できます

AbstractWordConverter.javaの790行でそのprocessImage(...)メソッドを見ると、そのメソッドが呼び出しているように見え、次に。という名前の別のメソッドが呼び出されているように見え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と Voilaを見るだけでした。 確かに期待どおりに機能しますが、リファクタリングと最適化が必要になる場合があります。

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 に答える