我打算将两个.docx文档合并为一个。文档1将提供页眉和页脚,而文档2将提供身体的其余部分。我有以下代码,但它以某种方式搞砸了结果文档。我收到错误消息,指出文档已损坏。有人可以查一下吗?这主要发生在我的文档1在页眉或页脚中有图像时。
WordprocessingMLPackage baseTemplatePkg = WordprocessingMLPackage
.load(baseTemplateInputStream);
HeaderPart headerPartToAdd = baseTemplatePkg
.getHeaderFooterPolicy().getFirstHeader();
FooterPart footerPartToAdd = baseTemplatePkg
.getHeaderFooterPolicy().getFirstFooter();
System.out.println("First headerPartToAdd: " + headerPartToAdd);
System.out.println("First footerPartToAdd: " + footerPartToAdd);
if (headerPartToAdd == null) {
System.out.println("Inside IF for Null first header.");
headerPartToAdd = baseTemplatePkg.getHeaderFooterPolicy()
.getDefaultHeader();
System.out.println("Default headerPartToAdd: "
+ headerPartToAdd);
}
if (footerPartToAdd == null) {
System.out.println("Inside IF for Null first footer.");
footerPartToAdd = baseTemplatePkg.getHeaderFooterPolicy()
.getDefaultFooter();
System.out.println("Default footerPartToAdd: "
+ footerPartToAdd);
}
clearHeaderAndFooterReference(sourceDocxPkg);
if (headerPartToAdd != null) {
HeaderPart newHeaderPart = new HeaderPart(new PartName(
"/word/header1.xml"));
newHeaderPart.createBinderAndJaxbElement(headerPartToAdd
.getContents());
newHeaderPart.setJAXBContext(headerPartToAdd.getJAXBContext());
Relationship headerRelationship = sourceDocxPkg
.getMainDocumentPart().addTargetPart(newHeaderPart);
System.out.println("headerRelationship: " + headerRelationship);
createHeaderReference(headerRelationship, sourceDocxPkg,HdrFtrRef.FIRST);
}
方法clear从文档2中删除所有页眉和页脚关系。我打算仅添加/设置结果文档的第一个页眉和页脚。
private static void clearHeaderAndFooterReference(
WordprocessingMLPackage wordMLPackage) {
MainDocumentPart mdp = wordMLPackage.getMainDocumentPart();
// Remove from sectPr
SectPrFinder finder = new SectPrFinder(mdp);
new TraversalUtil(mdp.getContent(), finder);
for (SectPr sectPr : finder.getSectPrList()) {
sectPr.getEGHdrFtrReferences().clear();
}
// Remove rels
List<Relationship> hfRels = new ArrayList<Relationship>();
for (Relationship rel : mdp.getRelationshipsPart().getRelationships()
.getRelationship()) {
if (rel.getType().equals(Namespaces.HEADER)
|| rel.getType().equals(Namespaces.FOOTER)) {
hfRels.add(rel);
}
}
for (Relationship rel : hfRels) {
System.out.println("rel: " + rel.getType());
mdp.getRelationshipsPart().removeRelationship(rel);
System.out.println("rel: " + rel.toString() + " removed!");
}
}
虽然带有图像的Document 1标题似乎是主要的罪魁祸首,但我不确定,因为在另一种情况下我只尝试过一个非常简单的标题。有人可以帮我解决这个问题吗?