Getting an illegal argument exception adding a header


I’m trying to add a primary header to a document. It works fine
if the document is empty. If I add a couple sections to the
document before I add the header I get this exception on the last line of code below:

java.lang.IllegalArgumentException: Cannot insert a node of this type at this location.

Do I need to set anything special on the sections? Any idea why this only works for empty documents?

Here’s a code snippet:

DocumentBuilder builder = new DocumentBuilder(document);


Node node = document.importNode(header, true,





Please mind that adding header/footer will fail if you already have the header/footer of this type in the section. In this case you need to either remove the already existing header/footer or copy header/footer child nodes to the existing header/footer one by one.

Best regards,


I tried adding this line before adding the header:


I still get the same error. Is there another method I should be using to remove the HeadersFooters?



Please clarify - are you adding the header from another document?


Yes, I get the header from another document and call

HeaderFooter header = (HeaderFooter) document.importNode(headerFromAnotherDoc, true,





Please hold on a little longer. I am trying to reproduce the error and find out if there is a fix or workaround.

Best regards,


ClearHeadersFooters does not removes headers/footers from section, just clears their content. To remove all headers/footers from section use HeadersFooters.Clear(). To remove header/footer of the particular type use HeadersFooters[HeaderFooterType].Remove() . For example,

HeaderFooter header = (HeaderFooter)doc.ImportNode(doc2.FirstSection.HeadersFooters[HeaderFooterType.HeaderPrimary], true, ImportFormatMode.UseDestinationStyles);



(All code declarations are in C#, but in Java they will be practically the same.)

Best regards,


That fixed the problem. Thank you!