我正在使用docx4j api
创建docx
文件。我已成功将一个docx
内容复制到了另一个。
对于复制标题内容,我得到标题文本。
但是我的要求也是复制标题图像。我怎样才能做到这一点?
我正在使用下面的代码复制标题-
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);
,但是此代码不复制图像。任何帮助表示赞赏。
答案 0 :(得分:0)
尝试类似(未经测试)的内容:
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);
}