Is there any way to clear content but preserve line feed in headers and footers

I am using aspose-words:21.2:jdk17.
Is there any way by which we can preserve line feed but remove rest of the content from all the 3 types of headers and footers? I just want to empty the section. I tried with couple of options but in all of them I am losing line feeds.

@nobilex Could you please attach your input and expected output documents here for our reference? We will check the documents and provide you more information.

before.docx (9.9 KB)

after.docx (8.2 KB)

@nobilex You can use the following code to remove text, leaving the paragraphs in the header:

Document doc = new Document("C:\\Temp\\in.docx");
// Get header.
HeaderFooter headerPrimary = doc.getFirstSection().getHeadersFooters().getByHeaderFooterType(HeaderFooterType.HEADER_PRIMARY);
// Remove all text from the header, leaving empty paragraphs.
if(headerPrimary!=null)
    headerPrimary.getChildNodes(NodeType.RUN, true).clear();
        
doc.save("C:\\Temp\\out.docx");

The above code supposes there is only textual content in the header. Alternative you can use the following approach:

Document doc = new Document("C:\\Temp\\in.docx");
// Get header.
HeaderFooter headerPrimary = doc.getFirstSection().getHeadersFooters().getByHeaderFooterType(HeaderFooterType.HEADER_PRIMARY);
// Remove all text from the header, leaving empty paragraphs.
if (headerPrimary != null)
{
    for (Paragraph p : (Iterable<Paragraph>)headerPrimary.getChildNodes(NodeType.PARAGRAPH, true))
        p.removeAllChildren();
}

doc.save("C:\\Temp\\out.docx");

if it is required to preserve also a soft line break, you can use code like this:

Document doc = new Document("C:\\Temp\\in.docx");
// Get header.
HeaderFooter headerPrimary = doc.getFirstSection().getHeadersFooters().getByHeaderFooterType(HeaderFooterType.HEADER_PRIMARY);
// Remove all text from the header, leaving empty paragraphs.
if (headerPrimary != null)
{
    for (Paragraph p : (Iterable<Paragraph>)headerPrimary.getChildNodes(NodeType.PARAGRAPH, true))
    {
        for (Node child : (Iterable<Node>)p.getChildNodes(NodeType.ANY, false))
        {
            if (child.getNodeType() == NodeType.RUN)
            {
                Run r = (Run)child;
                if (r.getText().contains(ControlChar.LINE_BREAK))
                {
                    r.setText(ControlChar.LINE_BREAK);
                    continue;
                }
            }
            child.remove();
        }
    }
}

doc.save("C:\\Temp\\out.docx");