How do I modify word documents using rust libraries?

Either with this crate: GitHub - cstkingkey/docx-rs: A Rust library for parsing and generating docx files.

or this crate: Body in docx_rust::document - Rust

I am not too sure how to open up an existing document file and replace texts.

Are either one of these the right libraries or is there another library that can do this for me?

The second one seems to do what you want.

How do I open a document file using the 2nd crate?

You can check the examples in the documentation.

1 Like

I got these two lines of code:

    let tmp = DocxFile::from_file("Sample.docx").unwrap();
    let mut file = tmp.parse().unwrap();

But I am not too sure how do I replace the text:

I am reading from here but when I am tying in file.replace_text.... this is not valid like there is no method under file.

I have this code:

let tmp = DocxFile::from_file("Sample.docx").unwrap();
let mut file = tmp.parse().unwrap();

However I am getting this error when I run the program:

thread 'main' panicked at src/main.rs:25:32:
called Result::unwrap() on an Err value: Xml(MissingField { name: "GradFill", field: "rotate_with_shape" })
note: run with RUST_BACKTRACE=1 environment variable to display a backtrace

It turns out I get this error if I saved the file using only offfice, not microsoft office so is there a way around this issue?

Based on what you've said, this seems to be the result of incompatibilities between the crate you're using and OnlyOffice. First you need to identify whether the bug is with OnlyOffice or the crate you're using. Then convince the maintainer of the crate or OnlyOffice to fix the problem, or fork their repo and fix it yourself.

Based on the error its like inside the document file (which is an archive) there are fields that are simply different that the crate was not designed to handle.

Yes, that's what I meant by incompatibility.

I believe that parse() is like filling a structure so is there another way around this to still be able to parse it? Even if I have to manually fill the structures?

If you need to convert between file formats, I suggest considering using a tool built for this purpose, rather than implementing this in Rust. The one I hear about the most is pandoc:

Perhaps you could to use a tool like this as an intermediate step in whatever you're doing, and then use Rust for other pieces of the implementation.

1 Like