first of all: docx4j is great, works really fine for me
But i have a problem:
I have an docx-file and set xml-data into it to bind it(= xpath) by using the opendope Plugin. After some time the data-xml changes (for example new data-fields have been added) and i don't want to create a new document and bind all fields again. I'd like to use the document, where i already have bind my fields to the xml-data and just want to exchange the xml-data. After exchanging the datafile i just want tobind the added field and the new field is supported by the document. But this doesn't work at the moment, here's my source:
- Code: Select all
public byte[] enrichDocxWithXML(byte[] docx, DocumentType documentType) throws DocumentTemplateException {
try {
ByteArrayInputStream documentTemplateInputStream = new ByteArrayInputStream(docx);
WordprocessingMLPackage wordMLPackage = Docx4J.load(documentTemplateInputStream);
CustomXmlDataStoragePart customXmlDataStoragePart = __injectCustomXmlDataStoragePart(wordMLPackage.getMainDocumentPart(),
this.documentDataXMLConverterService.getXML(documentType));
__addProperties(customXmlDataStoragePart);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Docx4J.save(wordMLPackage, outputStream, Docx4J.FLAG_NONE);
return outputStream.toByteArray();
} catch (Docx4JException ex) {
logger.error("Error at enriching document with xml file.", ex);
}
}
private void __addProperties(CustomXmlDataStoragePart customXmlDataStoragePart) throws InvalidFormatException {
CustomXmlDataStoragePropertiesPart part = new CustomXmlDataStoragePropertiesPart();
ObjectFactory of = new ObjectFactory();
DatastoreItem dsi = of.createDatastoreItem();
String newItemId = "{MyData}";
dsi.setItemID(newItemId);
part.setJaxbElement(dsi);
customXmlDataStoragePart.addTargetPart(part);
}
private CustomXmlDataStoragePart __injectCustomXmlDataStoragePart(MainDocumentPart parent, byte[] xmlData) throws Docx4JException {
CustomXmlDataStoragePart customXmlDataStoragePart = new CustomXmlDataStoragePart();
CustomXmlDataStorage data = new CustomXmlDataStorageImpl();
data.setDocument(new ByteArrayInputStream(xmlData));
customXmlDataStoragePart.setData(data);
parent.addTargetPart(customXmlDataStoragePart, AddPartBehaviour.RENAME_IF_NAME_EXISTS);
return customXmlDataStoragePart;
}
Sometimes it works to replace it but most of the time not. I tried to use the different AddPartBehaviour but none of them worked like i want. And if i try to enrich and document, which has already been enriched by this method, i can be written but cannot be opened by word without error.
Any idea what's wrong?
Thanks in advance.
BR
Nicky