Remove the headers and footers from a word processing document
Headers and footers are separate parts related from the main document part and referenced from section properties.
Removing headers and footers requires both package and document XML changes. Deleting only the parts leaves orphaned headerReference or footerReference elements; deleting only the references can leave unused parts in the package.
Section references
<w:sectPr>
<w:headerReference w:type="default" r:id="rId5"/>
<w:footerReference w:type="default" r:id="rId6"/>
</w:sectPr>
Rust workflow
Delete the related header and footer parts, then remove the corresponding references from section properties:
#![allow(unused)] fn main() { pub fn remove_headers_and_footers(path: &Path) -> Result<Vec<u8>, Box<dyn std::error::Error>> { let mut document = WordprocessingDocument::new_from_file_with_settings(path, lazy_settings())?; let main_part = document.main_document_part()?; let header_parts: Vec<_> = main_part.header_parts(&document).collect(); let footer_parts: Vec<_> = main_part.footer_parts(&document).collect(); for header_part in header_parts { main_part.delete_part(&mut document, header_part)?; } for footer_part in footer_parts { main_part.delete_part(&mut document, footer_part)?; } let document_xml = main_part.data_as_str(&document)?.unwrap_or_default(); let updated_xml = remove_header_footer_references(document_xml); main_part.set_data(&mut document, updated_xml.into_bytes())?; let mut buffer = Cursor::new(Vec::new()); document.save(&mut buffer)?; Ok(buffer.into_inner()) } }
A document can contain multiple sections, and each section can have first-page, even-page, and default header/footer references. Remove all matching HeaderReference and FooterReference elements from every SectionProperties node.
In ooxmlsdk, MainDocumentPart::header_parts(&document) and MainDocumentPart::footer_parts(&document) traverse the related parts. Generated schema types include Header, Footer, HeaderReference, FooterReference, and SectionProperties.