#parser #generator #openxml

docx

A Rust library for parsing and generating docx files

11 releases (4 stable)

1.1.2 Apr 27, 2020
1.1.1 Apr 7, 2020
1.1.0 Mar 25, 2020
0.2.1 Nov 8, 2019
0.1.0 Aug 17, 2018

#1875 in Parser implementations

Download history 39/week @ 2024-03-11 36/week @ 2024-03-18 23/week @ 2024-03-25 40/week @ 2024-04-01 21/week @ 2024-04-08 31/week @ 2024-04-15 33/week @ 2024-04-22 25/week @ 2024-04-29 23/week @ 2024-05-06 34/week @ 2024-05-13 31/week @ 2024-05-20 22/week @ 2024-05-27 31/week @ 2024-06-03 25/week @ 2024-06-10 50/week @ 2024-06-17 31/week @ 2024-06-24

139 downloads per month
Used in office-crypto

MIT license

105KB
3K SLoC

GitHub Workflow Status Crates.io Document

docx

A Rust library for parsing and generating docx files.

Document

License

MIT


lib.rs:

A Rust library for parsing and generating docx files.

Create a new document

Use Docx::default to create a new empty Docx, then use Docx::write_file for saving it to a file.

use docx::document::Paragraph;
use docx::Docx;

let mut docx = Docx::default();

// create a new paragraph and insert it
let para = Paragraph::default().push_text("Lorem Ipsum");
docx.document.push(para);

docx.write_file("demo.docx").unwrap();

Also see: Docx::write.

Reading from files

Use DocxFile::from_file to extract content from docx files, then use DocxFile::parse to generate a Docx struct.

use docx::document::Paragraph;
use docx::DocxFile;

let docx = DocxFile::from_file("origin.docx").unwrap();
let mut docx = docx.parse().unwrap();

let para = Paragraph::default().push_text("Lorem Ipsum");
docx.document.push(para);

docx.write_file("origin_appended.docx").unwrap();

To reduce allocations, DocxFile::parse returns a Docx struct contains references to DocxFile itself. It means you have to make sure that DocxFile lives as long as its returned Docx:

use docx::DocxFile;

let mut docx_option = None;
{
    let docx_file = DocxFile::from_file("foo.docx").unwrap();
    let mut docx = docx_file.parse().unwrap();
    docx_option = Some(docx);
    // `docx_file` gets dropped here and code fails to compile
}
docx_option.unwrap().write_file("foo.docx").unwrap();

Also see: DocxFile::from_reader.

Similar Projects

bokuweb/docx-rs: A .docx file writer with Rust/WebAssembly.

License

MIT

Dependencies

~2.5–4MB
~64K SLoC