Page 1 of 1

Recreate docx from document.xml

PostPosted: Sun Mar 22, 2009 11:36 pm
by Erik Lundqvist
Hi All,

Is it possible to use docx4j to recreate/create a docx from a document.xml file?

Thanks

//Erik

Re: Recreate docx from document.xml

PostPosted: Mon Mar 23, 2009 10:07 am
by jason
Is it possible to use docx4j to recreate/create a docx from a document.xml file?


Sure; try something like:

Code: Select all
      String filename = "document.xml";
      String fileOut = "new.docx";
      
      // Create a package
      WordprocessingMLPackage wmlPack = new WordprocessingMLPackage();

      // Create main document part
      org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart wordDocumentPart
                       = new org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart();   

      // Make a JAXB Object out of the document.xml
      JAXBContext jc = Context.jc;
      Unmarshaller u = jc.createUnmarshaller();               
      u.setEventHandler(new org.docx4j.jaxb.JaxbValidationEventHandler());
      Object o = u.unmarshal( new File(filename ) );
                     // for other options, see http://java.sun.com/webservices/docs/1.6/api/javax/xml/bind/Unmarshaller.html
      
      // Attach it
      wordDocumentPart.setJaxbElement(o);
      
      // Add the main document part to the package relationships
      // (creating it if necessary)
      wmlPack.addTargetPart(wordDocumentPart);      
      
      // Now save the package
      wmlPack.save(new java.io.File(System.getProperty("user.dir") + fileOut) );



This should work provided your document.xml doesn't refer to styles, or contain images, hyperlinks, comments etc. If it does, you'll need to either strip those out, or create appropriate relationships.

Another approach you could take is to construct a Flat OPC file, and then create a WordML package out of that. See the ImportFromPackageFormat sample for details.

Re: Recreate docx from document.xml

PostPosted: Mon Mar 23, 2009 10:56 am
by Erik Lundqvist
Thank you Jason.
I'll give that a go when I am back from work.

The document.xml only contains a table, no images or other fancy stuff.

:)

Re: Recreate docx from document.xml

PostPosted: Tue Mar 24, 2009 11:57 am
by Erik Lundqvist
Flawless Victory!

Great job everyone on the docx4j team :)