@RajChauhan, in the code example that I posted I only replicate the footer of type HeaderFooterType.FooterPrimary, to preserve consistency across all Sections’ footers you must also replicate the HeaderFooterType.FooterFirst and HeaderFooterType.FooterEven, that will solve the issue with the First page in Section_4.
For the issue with the start page number you can count the pages and set the PageStartingNumber to match the value of the page counter, check how I did it in the following example:
// Load the document.
Document doc = new Document("C:\\Temp\\newDoc.docx");
Document clonDoc = (Document)doc.Clone(false);
short sectionCounter = 1;
int pageCounter = 1;
HeaderFooter? footer = null;
HeaderFooter? firstPageFooter = null;
foreach (Section sec in doc.Sections)
{
// Add the Section to the clone Document
Node node = clonDoc.ImportNode(sec, true, ImportFormatMode.KeepSourceFormatting);
clonDoc.AppendChild(node);
// Create a Document to be able to save each individual section
Document temp = (Document)clonDoc.Clone(false);
// Get the current footer of the section
var currentFooter = sec.HeadersFooters.FirstOrDefault(hf => ((HeaderFooter)hf).HeaderFooterType == HeaderFooterType.FooterPrimary) as HeaderFooter;
var currentFirstPageFooter = sec.HeadersFooters.FirstOrDefault(hf => ((HeaderFooter)hf).HeaderFooterType == HeaderFooterType.FooterFirst) as HeaderFooter;
sec.PageSetup.RestartPageNumbering = true;
sec.PageSetup.PageStartingNumber = pageCounter;
// Should add footer when the current section don't have any footer and the prevoius section had a footer to replicate
if (currentFirstPageFooter == null && firstPageFooter != null)
{
// Add the footer to the section
Node tempFooterNode = sec.Document.ImportNode(firstPageFooter, true, ImportFormatMode.KeepSourceFormatting);
sec.AppendChild(tempFooterNode);
}
else if (currentFirstPageFooter != null)
{
firstPageFooter = currentFirstPageFooter;
}
// Should add footer when the current section don't have any footer and the prevoius section had a footer to replicate
if (currentFooter == null && footer != null)
{
// Add the footer to the section
Node tempFooterNode = sec.Document.ImportNode(footer, true, ImportFormatMode.KeepSourceFormatting);
sec.AppendChild(tempFooterNode);
}
else if(currentFooter != null)
{
footer = currentFooter;
}
// Add the current Section to the Document
Node tempSection = temp.ImportNode(sec, true, ImportFormatMode.KeepSourceFormatting);
temp.AppendChild(tempSection);
// Skip the 2 firsts sections to start counting pages
if(sectionCounter > 2)
{
pageCounter += temp.PageCount;
}
// Save the Document containing only the section and increase the counter
temp.Save(@$"C:\\Temp\\Section_{sectionCounter++}.docx");
}
// Save the whole cloned Document
clonDoc.Save(@"C:\\Temp\\newDoc_cloned.docx");
Please notice that this solution is tightly coupled with the input document.