Reputation: 541
I am using docx4j api
for creating docx
file. I am successfully copied one docx
content to another.
For copy header content, i get header text.
But my requirement is also copy header image. how can i do this?
I am using below code to copy header-
WordprocessingMLPackage source = WordprocessingMLPackage.load(new File(
"D://PoC//Agenda Formats//test.docx"));
RelationshipsPart rp = source.getMainDocumentPart()
.getRelationshipsPart();
Relationship rel = rp.getRelationshipByType(Namespaces.HEADER);
HeaderPart headerPart = (HeaderPart)rp.getPart(rel);
HeaderPart newHeaderPart = new HeaderPart();
newHeaderPart.setContents(XmlUtils.deepCopy(headerPart.getContents()));
return wordprocessingMLPackage.getMainDocumentPart().addTargetPart(
newHeaderPart, AddPartBehaviour.RENAME_IF_NAME_EXISTS);
but this code not copy image. any help is appreciated.
Upvotes: 0
Views: 514
Reputation: 15878
Try something like (untested):
void attachHeader(HeaderPart sourcePart, WordprocessingMLPackage targetPkg) throws Docx4JException {
HeaderPart newHeaderPart = new HeaderPart();
newHeaderPart.setContents(XmlUtils.deepCopy(sourcePart.getContents()));
if (sourcePart.getRelationshipsPart()!=null) {
// clone the rels part
RelationshipsPart rp = sourcePart.getRelationshipsPart();
newHeaderPart.getRelationshipsPart(true).setContents(XmlUtils.deepCopy(rp.getContents()));
// copy/add each part
for (Relationship r : newHeaderPart.getRelationshipsPart().getContents().getRelationship()) {
// get the source part
Part part = sourcePart.getRelationshipsPart().getPart(r.getId());
// ensure it is loaded
if (part instanceof BinaryPart) {
((BinaryPart)part).getBuffer();
}
// You might need to clone this part depending on your use case, but here I'll just attach it to targetPkg
targetPkg.getParts().getParts().put(part.getPartName(), part);
// This simple approach won't work if the target package already contains a part with the same name
// To fix that, you'd need to rename the part (also in the rel)
part.setPackage(targetPkg);
part.setOwningRelationshipPart(newHeaderPart.getRelationshipsPart());
}
}
targetPkg.getMainDocumentPart().addTargetPart(newHeaderPart,
AddPartBehaviour.RENAME_IF_NAME_EXISTS);
}
Upvotes: 0