Replace {placeholders} and manage content inside .docx files.
-
Primitive: not a template engine, but can do quite a few transformations
Replace text, swap images,delete comments,flip checkboxes, insert custom markup -
Fast: single-pass, avoids recompression, uses Aho-Corasick internally, almost O(n)
No long time read issues like docx‑rs has -
Not memory-efficient (yet): operates on a byte stream without DOM tree allocation
Keeps the whole text in‑memory
use docx_template::DocxFile;
use serde::Serialize;
use std::error::Error;
fn main() -> Result<(), Box<Error>> {
let data = Data { crustacean: "🦀".into() };
let output = DocxFile::from_path("in.docx")?.into_template(data)?.render()?;
std::fs::write("output.docx", output)?;
Ok(())
}
#[derive(Serialize)]
struct Data {
crustacean: String
}
A naive approach to the problem is just calling xml.replace("{placeholder}", "🦀")
.
Which isn't 100% accurate, as placeholders can reside in multiple adjacent XML nodes like in the example below.
That's why this crate was made. It reads XML nodes, detects patterns, and applies transformations keeping the structural integrity.
<w:run>{place</w:run><w:run>holder}</w:run>
<w:run>🦀</w:run><w:run></w:run>
serde
(default) — usejson!
macro &Serialize
structs to create templatesdocx-rs
— insert markup defined by @bokuweb/docx‑rsdocx-rust
— insert markup defined by @cstkingkey/docx‑rust
name | description |
---|---|
@bokuweb/docx‑rs0.4.18 Apr 26, 2024 |
docx-template = { feature = ["docx-rs"] } |
@cstkingkey/docx‑rust0.1.8 May 21, 2024 |
docx-template = { feature = ["docx-rust"] } |
@yūdachi/docx1.1.2 Apr 27, 2020 |
💀 (forked by docx-rust) |
@kaisery/ooxmlsdk0.1.16 Oct 12, 2024 |
|
office-crypto | Allows decrypting password protected MS Office files |
ms-offcrypto-writer | Encrypting ECMA376/OOXML files with agile encryption |
Note
Office Open XML (also informally known as OOXML or Microsoft Open XML (MOX)) is a zipped, XML-based file format developed by Microsoft for representing spreadsheets, charts, presentations and word processing documents. The format was initially standardized by Ecma (as ECMA-376), and by the ISO and IEC (as ISO/IEC 29500) in later versions.