Merge Documents but not headers footers

Oct 2, 2013 at 6:45 PM
Hi,

I want to say first how great this tool is and how much it has helped me.

I have a problem that I hope you guys can help me with. I am trying to merge several documents together using DocumentBuilder. Lets say I have doc1 with some headers/footers and doc2 with no headers/footers. Then after merge, in the new mergedDoc, the doc2 part has the headers and footers of doc1.

I understand that this is the intended functionality but is there a way to turn it off? I can't set keepSections as false as that would also lose section breaks.

Thank you for taking the time to help with my problem.
Oct 4, 2013 at 9:05 AM
Hi,

I'm really happy this is helpful.

There is currently no way to have DocumentBuilder do what you want, out of the box. If you use keepSections, it will bring the headers/footers along with. However, there is a super-easy solution. Use DocumentBuilder with keepSections set to true, and then programmatically strip the headers/footers after DocumentBuilder finishes. You just need to find all sectPr elements and remove the header and footer references. The following code should do it:
var xDoc = wDoc.MainDocumentPart.GetXDocument();
xDoc.Descendants(W.sectPr).Elements(W.headerReference).Remove();
xDoc.Descendants(W.sectPr).Elements(W.footerReference).Remove();
If you want to, you can go find the relationships to the various headers and footers, remove the relationships, and remove the parts.

Or, the super-simple way to accomplish this - run the document through DocumentBuilder again. This will strip those headers and footers from the document.

Cheers, Eric
Oct 8, 2013 at 1:59 PM
Hey,

Sorry for the late response, I haven't had the chance to look at this till now. So, I tried your code in my program which seems to just strips all headers and footers from the documents.

This is a problem since I need to keep them, just not have them propagate to a document which doesn't have them. Is there any way to check when the BuildDocument function adds the header/footer and prevent it from doing so when the source document does not have them?

Thanks again for taking the time to help, I really appreciate it.
Jul 23, 2014 at 10:50 AM
Edited Jul 23, 2014 at 11:05 AM
I am having the same issue that aishsharma encountered and I think this over and realize that in one document there is only one type of header allowed, so the current implementation makes sense. you cannot keep all the headers of your docs after you merge them.