Skip to main content

hello_world_docx/
hello_world_docx.rs

1//! The simplest possible Word document: one paragraph, saved to a real
2//! `.docx` file, then read back to prove the file this crate wrote is
3//! valid and round-trips correctly.
4//!
5//! Run with: `cargo run -p office-toolkit --example hello_world_docx`
6
7use std::path::{Path, PathBuf};
8
9use office_toolkit::prelude::*;
10use office_toolkit::{OpenFile, SaveToFile};
11
12fn main() -> office_toolkit::Result<()> {
13    let path = output_path("hello_world.docx");
14
15    // `Document` and `Paragraph` both come from `office_toolkit::prelude`.
16    let document = Document::new().with_paragraph(Paragraph::with_text("Hello, world!"));
17    document.save_to_file(&path)?;
18    println!("Wrote {}", path.display());
19
20    // Read the file back to confirm it is a valid .docx.
21    let reopened = Document::open_file(&path)?;
22    let text = reopened
23        .paragraphs()
24        .next()
25        .map(|paragraph| paragraph.text());
26    println!("Read back: {text:?}");
27
28    Ok(())
29}
30
31/// Every example in this directory writes its output under
32/// `tests-data/output/`, resolved relative to this crate's own manifest so
33/// it works no matter what directory `cargo run` was invoked from.
34fn output_path(filename: &str) -> PathBuf {
35    Path::new(env!("CARGO_MANIFEST_DIR"))
36        .join("../../tests-data/output")
37        .join(filename)
38}