Page 1 of 1

Replacing document.xml - handling relationships

PostPosted: Mon Mar 19, 2012 4:09 am
by bsqfmv
Hi,

I'm trying to replace the document.xml for a given document. I have the following code based on the ImportForeignPart sample. It generates the resulting document however there is a problem when trying to open the document. Further investigation revealed that only the document.xml file exists under /word directory in the output document (all other files and directories are missing). Would appreciate your help on this.

Code: Select all
            
WordprocessingMLPackage template = WordprocessingMLPackage.load(new File(this.getServletContext().getRealPath("/") + "/template.docx"));
InputStream in = new FileInputStream(this.getServletContext().getRealPath("/") + "/[Content_Types].xml");
ContentTypeManager externalCtm = new ContentTypeManager();
externalCtm.parseContentTypesFile(in);
in = new FileInputStream(this.getServletContext().getRealPath("/") + "/document.xml");
Part foreignPart = Load.getRawPart(in, externalCtm, "word/document.xml", null);
template.getMainDocumentPart().addTargetPart(foreignPart);      
template.save(new File(this.getServletContext().getRealPath("/") + "/my_new_report.docx"));

Re: Replacing document.xml - handling relationships

PostPosted: Mon Mar 19, 2012 9:53 pm
by jason
Yes, well there could be other files ("parts") for headers/footers, images, numbering etc. You need to take care of these yourself.

Alternatively, the paid extension MergeDocx can do it for you. If you're interested in that, please contact me off list.

Re: Replacing document.xml - handling relationships

PostPosted: Tue Mar 20, 2012 8:48 pm
by bsqfmv
Thanks Jason.

Do you mean the core docx4j API does not contain functions to achieve this and it can only be done using MergeDocx?

If the above is not the case, I would really appreciate if you could provide a basic code snippet or at-least point me towards the relevant APIs for this.

Once again, many thanks for your help.

Re: Replacing document.xml - handling relationships

PostPosted: Tue Mar 20, 2012 9:51 pm
by jason
bsqfmv wrote:Do you mean the core docx4j API does not contain functions to achieve this and it can only be done using MergeDocx?


You can certainly add parts using the core docx4j API (in particular, AddTargetPart). And it is simple enough if you know you only need/want to deal with images say.

For your use case, which I understand to be replacing document.xml and its dependencies, you could use AlteredParts and Patcher.

But if you want to merge 2 or more source documents which could include any docx feature, MergeDocx is a least effort way of doing that.

Re: Replacing document.xml - handling relationships

PostPosted: Sun Mar 25, 2012 1:28 am
by bsqfmv
Thanks Jason.

Would you have any sample code that uses AlteredParts and Patcher please?