Runnable recipes
Fields with cached results
Fields store instructions and cached placeholders. A compatible viewer may update page numbers, references and tables of contents; rocx does not calculate them.
From the checkout:
cargo run --locked --example fields -- fields.docx
uv run python examples/fields.py fields.docx
use rocx::*;
fn main() -> Result<()> {
let output = std::env::args().nth(1).unwrap_or("fields.docx".into());
let name = BookmarkName::new("Introduction")?;
let instruction = Property::new(
"reference.instruction",
Value::future({
let name = name.clone();
async move { FieldInstruction::Reference(name) }
}),
);
let mut section = Section::new(vec![
Paragraph::from_children(vec![
RangeStart::bookmark(name.clone()).into(),
TextRun::new("Introduction").into(),
RangeEnd::bookmark(&name).into(),
])
.into(),
Paragraph::from_children(vec![
Field::new(
instruction.reference(),
vec![TextRun::new("Introduction (cached)").into()],
)
.with_properties(FieldProperties {
dirty: Some(true),
..Default::default()
})
.into(),
])
.into(),
Paragraph::from_children(vec![
Field::new(
FieldInstruction::TableOfContents,
vec![TextRun::new("Contents pending update").into()],
)
.with_properties(FieldProperties {
form: FieldForm::Complex,
dirty: Some(true),
locked: None,
})
.into(),
])
.into(),
]);
section.footers.insert(
HeaderFooterType::Default,
Footer::new(vec![
Paragraph::from_children(vec![
TextRun::new("Page ").into(),
Field::new(FieldInstruction::Page, vec![TextRun::new("1").into()]).into(),
TextRun::new(" of ").into(),
Field::new(FieldInstruction::NumPages, vec![TextRun::new("1").into()]).into(),
])
.into(),
])
.into(),
);
futures::executor::block_on(Document::new(vec![section.into()]).resolve())?.save(output)
}
import asyncio
import sys
from rocx import declarative as d
async def main() -> None:
"""Save typed bookmark references, a TOC request and footer page fields."""
reference = d.Field(instruction=lambda: d.FieldInstruction.reference("Introduction"),
children=[d.TextRun("Introduction (cached)")], dirty=True)
document = d.Document([d.Section(children=[
d.Paragraph(children=[d.RangeStart.bookmark("Introduction"), d.TextRun("Introduction"),
d.RangeEnd.bookmark("Introduction")]),
d.Paragraph(children=[reference]),
d.Paragraph(children=[d.Field(d.FieldInstruction.table_of_contents(),
[d.TextRun("Contents pending update")], form="complex", dirty=True)]),
], footers={"default": d.Footer(children=[d.Paragraph(children=[
d.TextRun("Page "), d.Field(d.FieldInstruction.page(), [d.TextRun("1")]),
d.TextRun(" of "), d.Field(d.FieldInstruction.num_pages(), [d.TextRun("1")]),
])])})])
await document.save(sys.argv[1] if len(sys.argv) > 1 else "fields.docx")
if __name__ == "__main__":
asyncio.run(main())
See the field contract for supported instructions, container restrictions and consumer update behavior. Other executable recipes cover ranges, notes, and deferred values.
Edit an existing document
Using the quickstart setup, replace {{name}} in an unsigned template.docx and save a new filled.docx. The placeholder may span adjacent runs.
use rocx::{Document, Error};
use rocx::application::DocumentTemplate;
use rocx::template::EditScope;
fn main() -> Result<(), Error> {
futures_executor::block_on(async {
let mut template = DocumentTemplate::new("template.docx");
template.edits.scope = EditScope::Body;
template.edits.replacements.push(("{{name}}".into(), "Ada".into()));
Document::new(vec![]).resolve().await?
.save_with_template("filled.docx", &template)
})
}
import asyncio
from rocx.declarative import Document, DocumentTemplate
async def main():
template = DocumentTemplate(
"template.docx", replacements={"{{name}}": "Ada"}, scope="body"
)
await Document([]).save("filled.docx", template)
asyncio.run(main())
Choose the body scope for body paragraphs only. Broader scopes include headers and footers, or related comments, footnotes and endnotes. Ordinary replacement can span runs inside a hyperlink but cannot cross structured boundaries. For protected content, use the revision or tagged control APIs. See what survives an edit.