cstkingkey / docx-rs

A Rust library for parsing and generating docx files.
MIT License
12 stars 12 forks source link

Update text in headers, tables.. #5

Closed FransHk closed 10 months ago

FransHk commented 10 months ago

Just a quick two cents for who may need this. This PR integrates the existing text replacement methods for headers and for table content.

After parsing a docx like so:

let docx = match DocxFile::from_file("{path}/temp.docx") {
        Ok(file) => file,
        Err(e) => {
            eprintln!("Failed to open file: {:?}", e);
            return;
        }
    };

    let mut parsed_docx = match docx.parse() {
        Ok(parsed) => parsed,
        Err(e) => {
            eprintln!("Failed to parse file: {:?}", e);
            return;
        }
    };

We can replace text in the doc body and in its header(s) using a replacement hashmap, for example:

    // Obtain all header .xml file keys ("header1.xml...")
    // so that we can iteratively access them later
    let hkeys: Vec<String> = parsed_docx.headers.keys().cloned().collect();

    // Iterate over the replacement hashmapc
    // that contains (old, new) key-value entries
    for (key, val) in &replacement_map {
        parsed_docx.document.body.replace_text_simple(key, val);
        // For each document header, attempt to replace all
        // required text entries contained in the replacement map
        for header_key in &hkeys {
            parsed_docx
                .headers
                .get_mut(header_key)
                .expect("Replacing header text failed") 
                .replace_text_simple(key, val);
        }
    }

This was previously only possible for BodyContent::Paragraph, which is simply all paragraphs in the body excluding cell-based content and/or headers.