Clear headers and footers per section

I am trying to insert new documents, images, or pieces of text into a document. After each major section (section break new page)…I want to reset the formatting and remove headers/footers for new sections, but this code it not working…if I insert a document with a header and then an image in a new section, the header carries over to the page with the image on it.

using Aspose.Words;
using Azure.Storage.Blobs;
using DocumentGenerationTestExample.Services;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json;

namespace DocumentFromManifestService.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class DocumentController : ControllerBase
    {
        private readonly IConfiguration _configuration;
        private readonly BlobFileService _blobFileService;

        public DocumentController(IConfiguration configuration)
        {
            _configuration = configuration;
            var connectionString = _configuration["AzureBlobStorage:ConnectionString"];
            var containerName = _configuration["AzureBlobStorage:ContainerName"];
            _blobFileService = new BlobFileService(new BlobServiceClient(connectionString), containerName);
            SetLicense();
        }

        private static void SetLicense()
        {
            var license = new License();
            license.SetLicense("Licenses/license.lic");
        }

        [HttpPost("generate")]
        public async Task<IActionResult> GenerateDocumentFromManifest([FromBody] JsonElement manifest)
        {
            var doc = new Document();
            var builder = new DocumentBuilder(doc);
            string lastMajorNumber = null;
            foreach (var item in manifest.EnumerateArray())
            {
                var number = item.GetProperty("number").GetString();
                var nameContent = item.GetProperty("nameContent").GetString();
                var type = item.GetProperty("type").GetString();
                var details = item.GetProperty("details").GetString();

                var currentMajorNumber = number.Split('.')[0];
                Section section;
                if (lastMajorNumber != null && currentMajorNumber != lastMajorNumber)
                {
                    builder.InsertBreak(BreakType.SectionBreakNewPage);
                    section = builder.CurrentSection;
                }
                else if (lastMajorNumber != null && currentMajorNumber == lastMajorNumber)
                {
                    builder.InsertBreak(BreakType.SectionBreakContinuous);
                    section = builder.CurrentSection;
                }
                else
                {
                    section = builder.CurrentSection;
                }
                ResetSectionFormatting(section);
                if (type == "Image" || type == "Word")
                {
                    string tempFilePath = await _blobFileService.DownloadFileToTempAsync(nameContent);
                    ProcessContent(builder, type, tempFilePath);
                    System.IO.File.Delete(tempFilePath);
                }
                else if (type == "Text")
                {
                    builder.Writeln(nameContent);
                }
                lastMajorNumber = currentMajorNumber;
            }
            var outputStream = new MemoryStream();
            doc.Save(outputStream, SaveFormat.Docx);
            outputStream.Position = 0;
            return File(outputStream.ToArray(), "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "GeneratedDocument.docx");
        }

        private static void ResetSectionFormatting(Section section)
        {
            section.ClearHeadersFooters();
            foreach (HeaderFooter hf in section.HeadersFooters)
            {
                hf.IsLinkedToPrevious = false;
            }
            PageSetup pageSetup = section.PageSetup;
            pageSetup.ClearFormatting();
        }

        private static void ProcessContent(DocumentBuilder builder, string type, string filePath)
        {
            if (type == "Image")
            {
                builder.InsertImage(filePath);
            }
            else if (type == "Word")
            {
                Document subDoc = new Document(filePath);
                builder.InsertDocument(subDoc, ImportFormatMode.KeepSourceFormatting);
            }
        }
    }
}

I think some of the issue might be because of linking between section headers/footers, but not sure how to fix.
ExampleNotFixed.docx (284.6 KB)

ExampleFixed.docx (275.8 KB)

@amattice The problem occurs because you insert document into an empty section, page setup of the inserted document are used. So to get the expected output you should reset formatting f the first section of the source document. Please see the following simplified code:

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert document with header/footer
builder.InsertDocument(new Document(@"C:\Temp\header.docx"), ImportFormatMode.KeepSourceFormatting);

// Insert section break
builder.InsertBreak(BreakType.SectionBreakNewPage);

// Insert another document without header/footer
Document src = new Document(@"C:\Temp\src.docx");
ResetSectionFormatting(src.FirstSection);
builder.InsertDocument(src, ImportFormatMode.KeepSourceFormatting);

doc.Save(@"C:\Temp\out.docx");
private static void ResetSectionFormatting(Section section)
{
    PageSetup pageSetup = section.PageSetup;
    pageSetup.ClearFormatting();

    section.ClearHeadersFooters();
    section.HeadersFooters.LinkToPrevious(false);
}

The issue with this is I don’t know which order the source documents will be in, so I can’t say which will have the headers and which won’t. I need each document to keep their source headers and footers, but not be affected by other documents headers and footers. That’s why I was hoping each could be a section on a new page and clear the previous sections headers and footers before inserting the new document. That way if it is a word document, the new headers and footers are inserted if it has it…or if it is an image or a word document without a header or footer, the headers and footers get removed before inserting them.

@amattice In this case you should modify the code like this:

private static void ResetSectionFormatting(Section section)
{
    PageSetup pageSetup = section.PageSetup;
    pageSetup.ClearFormatting();

    section.HeadersFooters.LinkToPrevious(false);
}

It is not required to clear headers/footer, you should simply unlink them from previous section. In such case if source document has headers/footers they will be there, if not, headers/footers will be empty.

@alexey.noskov Ok, and what about when I am inserting an image and there is no “source” document, and we are just inserting the image into the new section. How do I make sure my headers don’t carry over?

@amattice In this case you should insert a section break before inserting and image and unlink headers/footers of the newly created section.