Open and add text to a word processing document

Adding text means editing the main document XML, usually by inserting a new paragraph or run under <w:body/>.

The main document part contains the text of the document as WordprocessingML. Opening a package for editing is only the first step; a writer must ensure the document root and body exist before appending content.

Text markup

<w:p>
  <w:r><w:t>New text</w:t></w:r>
</w:p>

Rust workflow

#![allow(unused)]
fn main() {
pub fn add_paragraph_text(path: &Path, text: &str) -> 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 xml = main_part.data_as_str(&document)?.unwrap_or_default();
  let paragraph = paragraph_xml(text);
  let updated_xml = insert_before_section_properties(xml, &paragraph)?;

  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())
}
}

The listing appends a paragraph before a trailing <w:sectPr/> if the body has section properties. A broader writer should also handle documents with missing or unusual body structure, and can build the paragraph from generated schema types instead of raw XML strings.

Unlike the upstream .NET SDK's AutoSave behavior, this book shows explicit save behavior through document.save(...).