Page 1 of 1

Copy Header/Footer from template docx to another

PostPosted: Mon Jan 14, 2019 8:58 pm
by dermaga
I want to copy the complete Header from the template docx file and replace with it the header from the main docx file.
At the moment I have no idea how to do this because I do not have much experience with docx4j.

Current code status for removing header:
final WordprocessingMLPackage wordProcessingPackageHeader = DocxUtils
.getWordProcessingPackage(DocxUtils.class.getResourceAsStream("main-document.docx"));
Code: Select all
final RelationshipsPart relationshipsPart = wordProcessingPackageHeader.getMainDocumentPart().getRelationshipsPart();
final List<Relationship> relationships = relationshipsPart.getRelationships().getRelationship();

for (final Relationship r : relationships) {
     if (r.getType().equals(Namespaces.HEADER)) {
           final Part part = relationshipsPart.getPart(r);
           part.remove();
     }
}


Is it necessary to remove the header before setting it or can I also replace it?
How could I remove the header of the main document and then set the header from the template doc?

Re: Copy Header/Footer from template docx to another

PostPosted: Mon Jan 14, 2019 11:19 pm
by adams
Hi,

I think you can do it like this:
Code: Select all
List<Object> templateContent;
for (SectionWrapper section : templateWordMLPackage.getDocumentModel().getSections()) {
    if (section.getHeaderFooterPolicy() != null) {
        //you should null check every step
        //header content form template
        templateContent = section.getHeaderFooterPolicy().getDefaultHeader().getContent();  //or getDefaultFooter()
    }
}
//this is the content you want to insert to your another document. open that too and do the same

List<Object> content;
for (SectionWrapper section : wordMLPackage.getDocumentModel().getSections()) {
    if (section.getHeaderFooterPolicy() != null) {
        //you should null check every step
        //header content form template
        content = section.getHeaderFooterPolicy().getDefaultHeader().getContent();  //or getDefaultFooter()
    }
}

content.clear();
content.addAll(templateContent);


Re: Copy Header/Footer from template docx to another

PostPosted: Tue Jan 15, 2019 1:40 am
by dermaga
Thanks for your response.

The main document do not have any header so I cant call:
Code: Select all
content = section.getHeaderFooterPolicy().getDefaultHeader().getContent();

cause getDefaultHeader() returns null.

How can I add the templateContent to content List when the List<Object> content remains null?