Remove Header when appending documents

Hi ,

I am trying to append multiple documents ( doc1.doc, doc2.doc) to the main.doc document.

doc1.doc has header with contents and doc2.doc have empty header .

doc.appendDocument(doc1, ImportFormatMode.KEEP_SOURCE_FORMATTING );
doc.appendDocument(doc2, ImportFormatMode.KEEP_SOURCE_FORMATTING );

Once document appended, I can see doc2.doc also having the header which comes from the doc1.doc .

How to remove unnecessary headers from the main document ?

@Chaminda When you use Document.appendDocument method sections from the source document are added into the destination document keeping original sections page setup. By default if following sections in MS Word does not have headers/footers, they are inherited from the previous section. That is why you see headers/footers from your MS Word document in the appended documents. You can disable this using HeaderFooterCollection.linkToPrevious method. Your code should look like this:

// Open destination document
Document dst = new Document("dst.docx");
// Load source document. 
Document src = new Document("src.docx");
        
// Disable headers/footers inheriting.
src.getFirstSection().getHeadersFooters().linkToPrevious(false);
        
dst.appendDocument(src, ImportFormatMode.KEEP_SOURCE_FORMATTING);

Thanks for the prompt reply . It works !!

1 Like