How to save images from a Word document in DOCX4J

I try to go through a word document and save all the images found in the word document. I tried uploading a sample word document to an online demo and noticed that the images are listed as:

/word/media/image1.png  rId5    image/png
/word/media/image2.png  rId5    image/png
/word/media/image3.jpg  rId5    image/jpeg

How can I programmatically save these images while moving a document?

Currently, I am getting all the text from the document as follows:

   WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(filePath))
   MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart()
   Document wmlDocumentEl = (org.docx4j.wml.Document)documentPart.getJaxbElement()
   Body body =  wmlDocumentEl.getBody();
   DocumentTraverser traverser = new DocumentTraverser();

   class DocumentTraverser  extends TraversalUtil.CallbackImpl {
      @Override
      public List<Object> apply(Object o) {
         if (o instanceof org.docx4j.wml.Text) {
         ....
         }
         return null;
      }
   }
+4
source share
2 answers

For embedded (as opposed to external) images, the simplest approach is:

import java.io.FileOutputStream;
import java.util.Map.Entry;

import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.Part;
import org.docx4j.openpackaging.parts.PartName;
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPart;
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;

public class SaveImages  {

        public static void main(String[] args) throws Exception {

            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));

            for (Entry<PartName, Part> entry : wordMLPackage.getParts().getParts().entrySet()) {

                if (entry.getValue() instanceof BinaryPartAbstractImage) {

                    FileOutputStream fos = new FileOutputStream( yourfile ); // TODO: you can get file extension from PartName, or part class.
                    ((BinaryPart)entry.getValue()).writeDataToOutputStream(fos);
                    fos.close();

                }


            }
        }

    }

, (, MainDocumentPart, / .., ).

https://github.com/plutext/docx4j/blob/master/src/samples/docx4j/org/docx4j/samples/ImageConvertEmbeddedToLinked.java , . , XML. XML DrawingML VML.

+1

.docx, :

◾ .docx, Word 2007 Word (*.docx). ◾ .docx .zip, D.

0

All Articles