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.