Page 1 of 1

Replacing document.xml content in docx

PostPosted: Tue Apr 20, 2010 6:54 am
by stuart.ledwich
Is it possible to do the following with docx4j

1. Open an existing .DOCX file (WordprocessingMLPackage.load(docxFile))
2. Discard the current /word/document.xml
3. Replace with a new /word/document.xml file (stored as a string)

Any help or guidance much appreciated.

Re: Replacing document.xml content in docx

PostPosted: Tue Apr 20, 2010 9:25 pm
by jason
Sure.

Its easiest when the original document.xml and the replacement have the same relationships.

In this simple case, you could either replace the JAXB element, or replace the MainDocumentPart.

Replacing the jaxbElement would be simpler. The problem with doing this is that there are some objects in the MainDocumentPart which are constructed when they are first requested (eg styleTree, propertyResolver), so if you've done something which has caused these to be created, you don't want to end up using these stale objects.

So better to replace the main document part. How about something like the following (untested):

Code: Select all
      // Keep existing relationships
      RelationshipsPart rp = wordMLPackage1.getMainDocumentPart().getRelationshipsPart();

      // We'll reuse the rel pointing to the MDP;
      Relationship sourceRel = wordMLPackage1.getMainDocumentPart().getSourceRelationship();

      // Create main document part
      MainDocumentPart wordDocumentPart = new MainDocumentPart();      
      wordMLPackage1.getParts().put(wordDocumentPart);
      wordDocumentPart.setPackage( wordMLPackage1 );

      // Set shortcut to mdp
      wordMLPackage1.setPartShortcut(wordDocumentPart, Namespaces.DOCUMENT);

      // Reconnect the rels
      wordDocumentPart.setSourceRelationship(sourceRel);
      
      // Attach existing rels - this assumes existing rels are still relevant,
      // and the new MDP doesn't contain any additional rel references
      // or style references (not already in use in the existing doc)
      wordDocumentPart.setRelationships(rp);

      // TODO: setup part shortcuts on new MDP, if required
      // See DocumentPart for how to do this      
      
      // Put the content in the part
      wordDocumentPart.setJaxbElement(
            (org.docx4j.wml.Document)XmlUtils.unmarshalString( yourDocumentXmlString ));


Re: Replacing document.xml content in docx

PostPosted: Tue Apr 20, 2010 10:10 pm
by stuart.ledwich
Great! thank you so much - it worked perfectly.

Re: Replacing document.xml content in docx

PostPosted: Thu Dec 02, 2010 5:25 am
by vikash_me
Hi,

This is excactly what I am looking for my solution. But, I am not able to use this as this is written in Java and I am developing my solution in .net.

Can someone pls guide me how to implement the same in .net? any guideline?

Thanks,

Vikash