pub struct Document {Show 19 fields
pub blocks: Vec<Block>,
pub header: Option<HeaderFooter>,
pub footer: Option<HeaderFooter>,
pub header_first: Option<HeaderFooter>,
pub footer_first: Option<HeaderFooter>,
pub header_even: Option<HeaderFooter>,
pub footer_even: Option<HeaderFooter>,
pub page_setup: PageSetup,
pub styles: Vec<Style>,
pub numbering_definitions: Vec<NumberingDefinition>,
pub footnotes: Vec<Note>,
pub endnotes: Vec<Note>,
pub comments: Vec<Comment>,
pub theme: Option<Theme>,
pub track_changes: bool,
pub properties: DocumentProperties,
pub protection: Option<ProtectionKind>,
pub extended_properties: ExtendedProperties,
pub custom_properties: Vec<(String, CustomPropertyValue)>,
}Expand description
A .docx document: a sequence of block-level content (paragraphs and tables), in reading order,
plus an optional default header/footer and a set of named styles (word/styles.xml)
paragraphs/runs can refer to.
Fields§
§blocks: Vec<Block>The blocks that make up the document body, in order.
header: Option<HeaderFooter>The document’s default header (w:headerReference[@w:type='default']), shown on every page
unless a page-specific header overrides it (header_first/ header_even, below).
The document’s default footer, mirroring header.
header_first: Option<HeaderFooter>A header shown only on the section’s first page (w:headerReference[@w:type='first']),
overriding header for that one page. Setting this (or footer_first) automatically makes
the writer emit w:sectPr/w:titlePg (CT_OnOff) — without it, Word ignores the
first-type reference entirely and just repeats the default header, per ECMA-376.
A footer shown only on the section’s first page, mirroring header_first.
header_even: Option<HeaderFooter>A header shown only on even-numbered pages (w:headerReference[@w:type='even']) —
header/header_first become the odd-page headers once this is set. Setting this (or
footer_even) automatically makes the writer emit w:evenAndOddHeaders in
word/settings.xml (CT_OnOff) — without it, Word ignores the even-type reference and
just repeats the default/odd header on every page, per ECMA-376.
A footer shown only on even-numbered pages, mirroring header_even.
page_setup: PageSetupThis document’s page setup — size, orientation, margins, columns (w:sectPr’s
pgSz/pgMar/cols). Unlike header/footer, this is not optional: WordprocessingML
always needs some page setup, so Default gives the exact fixed A4/standard-margins
values this crate has always written since (PageSetup::default), preserving old behavior
for callers who don’t set this. Only a single, document-wide page setup is modeled —
WordprocessingML actually allows several independent page setups via mid-document section
breaks (a new w:sectPr inside a paragraph’s own w:pPr), deliberately not modeled here:
mid-document section breaks are a rare, advanced case, and supporting only a single
document-wide page setup keeps the model considerably simpler without real demand yet for
the alternative.
styles: Vec<Style>Named styles declared for this document (word/styles.xml, CT_Styles’s style elements),
referenced from paragraphs (Paragraph.style_id) and runs (Run.style_id) by id. Only
written if non-empty — see writer.rs.
numbering_definitions: Vec<NumberingDefinition>Numbering (list) definitions declared for this document (word/numbering.xml), referenced
from paragraphs (Paragraph.numbering_id) by id. Only written if non-empty — see
writer.rs.
footnotes: Vec<Note>Footnotes declared for this document (word/footnotes.xml), referenced from the body by id
(RunContent::NoteReference). Only written if non-empty — see writer.rs.
endnotes: Vec<Note>Endnotes declared for this document (word/endnotes.xml), mirroring footnotes.
comments: Vec<Comment>Comments declared for this document (word/comments.xml), anchored to a range of the body
via Run.comment_ids — see Comment’s doc comment for how the underlying
w:commentRangeStart/ w:commentRangeEnd/w:commentReference markers are derived from
that field rather than modeled by hand. Only written if non-empty — see writer.rs.
theme: Option<Theme>This document’s theme (word/theme/theme1.xml), or None to leave it unset entirely — a
document with no theme part still opens fine in Word, just falling back to whatever theme
Word’s own default template carries. Only written if Some — see writer.rs, and
Theme’s own doc comment for what is/isn’t modeled.
track_changes: boolWhether Word should track changes (insertions/deletions/formatting changes) made to this
document from now on (w:trackRevisions — confirmed via ECMA-376’s own CT_Settings schema
fragment and docx4j’s generated CTSettings binding; despite the UI calling the feature
“Track Changes”, the underlying element is not named w:trackChanges, easy to get wrong —
CT_OnOff, in word/settings.xml). This is only the simple on/off editing-mode toggle —
matching the equivalent checkbox under Word’s Review > Track Changes menu — not a way to
author individual tracked revisions (w:ins/w:del/w:rPrChange/..) programmatically;
this crate exposes exactly this one on/off toggle and nothing more — no API here creates
individual revision marks. false (the default) omits w:trackRevisions entirely, which is
equivalent to explicitly disabling it.
properties: DocumentPropertiesThis document’s core properties (docProps/core.xml, CT_CoreProperties — title, author,
subject, etc.). Left at its Default (every field None) writes the same near-empty
<cp:coreProperties/> this crate has always written; setting any field populates just that
element, since CT_CoreProperties is an xsd:all group (every child optional, no fixed
order — confirmed via ECMA-376’s own schema fragment, unlike the many strict xsd:sequence
groups this project has had to pin down elsewhere).
protection: Option<ProtectionKind>This document’s editing-restriction protection (w:documentProtection, CT_DocProtect, in
word/settings.xml), or None for no restriction. Only the no-password form is modeled
(w:enforcement="1" with no w:cryptProviderType/hash/salt) — a password-protected variant
involves a cryptographic hash of the password plus a random salt, real complexity with no
proportionate demand seen yet in this project, matching the “simple case first” posture
already applied elsewhere (e.g. Run.text_border’s fixed appearance instead of
CT_Border’s full richness). See ProtectionKind for which restriction levels are
modeled.
extended_properties: ExtendedPropertiesThis document’s extended properties (docProps/app.xml, CT_Properties —
application-defined metadata, distinct from docProps/core.xml’s Dublin Core fields above).
Only Company/Manager are modeled — see ExtendedProperties’s own doc comment for why
the many statistical fields (Words/Pages/ Characters/..) aren’t. Left at its Default
(both fields None), this crate still always writes docProps/app.xml with just
Application set (unchanged from before this field existed) — see writer.rs’s
to_extended_properties_xml.
custom_properties: Vec<(String, CustomPropertyValue)>This document’s custom properties (docProps/custom.xml, CT_Properties — arbitrary
user-defined name/value metadata pairs). A Vec of (name, value) pairs, not a map — order
matters here: it determines the pid (property id) each entry gets when written (2, 3,
4. in declaration order; 0/1 are reserved by the format and never assigned), so
insertion order is preserved rather than an arbitrary hash-map order. Only written if
non-empty, same “optional part” convention as styles/footnotes/etc. See
CustomPropertyValue for which value types are modeled.
Implementations§
Source§impl Document
impl Document
Sourcepub fn new() -> Document
pub fn new() -> Document
Creates an empty document.
Examples found in repository?
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}More examples
18fn main() -> office_toolkit::Result<()> {
19 let path = output_path("docx_images_and_charts.docx");
20 let image_bytes = std::fs::read(image_fixture_path())?;
21
22 // 2 inches wide, 1.5 inches tall (914,400 EMU per inch).
23 let image = Image::new(image_bytes, ImageFormat::Png, 1_828_800, 1_371_600)
24 .with_description("Project test image");
25 let chart = EmbeddedChart::new(sample_chart_space(), 4_572_000, 2_743_200)
26 .with_name("Quarterly revenue");
27
28 let document = Document::new()
29 .with_paragraph(heading("An inline image", false))
30 .with_paragraph(Paragraph::new().with_run(Run::with_image(image)))
31 .with_paragraph(heading("An embedded bar chart", true))
32 .with_paragraph(Paragraph::new().with_run(Run::with_chart(chart)));
33
34 document.save_to_file(&path)?;
35 println!("Wrote {}", path.display());
36 Ok(())
37}14fn main() -> office_toolkit::Result<()> {
15 let default_theme_document = Document::new()
16 .with_theme(Theme::office_default())
17 .with_paragraph(Paragraph::with_text("Office's built-in default theme."))
18 .with_paragraph(Paragraph::with_text(
19 "Cambria for headings, Calibri for body text, the classic Office palette.",
20 ));
21 let default_path = output_path("docx_theme_default.docx");
22 default_theme_document.save_to_file(&default_path)?;
23 println!("Wrote {}", default_path.display());
24
25 // A custom, branded theme: a dark navy/orange palette and a different
26 // heading/body font pairing.
27 let custom_colors = ColorScheme::new(
28 "1B1B1B", "FFFFFF", "0A2540", "F5F5F5", "0A2540", "E8622C", "2E86AB", "6FB98F", "F4A259",
29 "8E4585", "1155CC", "6B3FA0",
30 );
31 let custom_fonts = FontScheme::new("Georgia", "Verdana");
32 let custom_theme_document = Document::new()
33 .with_theme(Theme::new("Custom Brand", custom_colors, custom_fonts))
34 .with_paragraph(Paragraph::with_text("A custom, branded theme."))
35 .with_paragraph(Paragraph::with_text(
36 "Georgia for headings, Verdana for body text, a navy/orange palette.",
37 ));
38 let custom_path = output_path("docx_theme_custom.docx");
39 custom_theme_document.save_to_file(&custom_path)?;
40 println!("Wrote {}", custom_path.display());
41
42 Ok(())
43}16fn main() -> office_toolkit::Result<()> {
17 let properties = DocumentProperties::new()
18 .with_title("Quarterly Report")
19 .with_subject("Q3 results")
20 .with_creator("Jane Doe")
21 .with_keywords("finance, quarterly, report")
22 .with_description("An example document showing document properties.")
23 .with_category("Finance")
24 .with_content_status("Draft");
25 let extended_properties = ExtendedProperties::new()
26 .with_company("Acme Corp.")
27 .with_manager("Jane Manager");
28
29 let metadata_document = Document::new()
30 .with_properties(properties)
31 .with_extended_properties(extended_properties)
32 .with_custom_property("ProjectCode", CustomPropertyValue::Text("Q3-2026".to_string()))
33 .with_custom_property("Budget", CustomPropertyValue::Number(125_000.0))
34 .with_custom_property("Approved", CustomPropertyValue::Bool(false))
35 .with_custom_property("RevisionCount", CustomPropertyValue::Int(3))
36 .with_track_changes(true)
37 .with_paragraph(Paragraph::with_text(
38 "This document carries standard properties (title/author/subject/...), four custom properties, \
39 and has track changes turned on — check File > Info in Word to see them.",
40 ));
41 let metadata_path = output_path("docx_metadata.docx");
42 metadata_document.save_to_file(&metadata_path)?;
43 println!("Wrote {}", metadata_path.display());
44
45 let protected_document = Document::new()
46 .with_protection(ProtectionKind::ReadOnly)
47 .with_paragraph(Paragraph::with_text(
48 "This document is protected as read-only — Word will ask for a password before allowing edits.",
49 ));
50 let protected_path = output_path("docx_protected.docx");
51 protected_document.save_to_file(&protected_path)?;
52 println!("Wrote {}", protected_path.display());
53
54 Ok(())
55}15fn main() -> office_toolkit::Result<()> {
16 let path = output_path("docx_page_layout.docx");
17
18 let page_setup = PageSetup::new()
19 .with_size_twips(16_838, 11_906) // A4 landscape, in twentieths of a point
20 .with_orientation(Orientation::Landscape)
21 .with_margins_twips(1_440, 1_440, 1_800, 1_800) // top, bottom, left, right
22 .with_header_footer_margins_twips(720, 720)
23 .with_gutter_twips(0)
24 .with_columns(2);
25
26 let default_header =
27 HeaderFooter::new().with_paragraph(Paragraph::with_text("Default header — every page"));
28 let default_footer =
29 HeaderFooter::new().with_paragraph(Paragraph::with_text("Default footer — every page"));
30 let first_header = HeaderFooter::new()
31 .with_paragraph(Paragraph::with_text("First-page header — cover page only"));
32 let even_header = HeaderFooter::new().with_paragraph(Paragraph::with_text("Even-page header"));
33
34 let document = Document::new()
35 .with_page_setup(page_setup)
36 .with_header(default_header)
37 .with_footer(default_footer)
38 .with_header_first(first_header)
39 .with_header_even(even_header)
40 .with_paragraph(heading("Page setup: A4 landscape, custom margins, two columns", false))
41 .with_paragraph(Paragraph::with_text(
42 "This document is landscape A4, with wider left/right margins than top/bottom, and its body text \
43 flows in two columns. Look at the page in Word's Layout view to see the effect.",
44 ))
45 .with_paragraph(heading("Headers and footers", true))
46 .with_paragraph(Paragraph::with_text(
47 "Page 1 (this page) uses the first-page header, since \"different first page\" headers are set. \
48 Every other page uses the default header shown above, and every page uses the default footer.",
49 ))
50 .with_paragraph(heading("A third page, to see the default header again", true))
51 .with_paragraph(Paragraph::with_text(
52 "If Word is configured to show even/odd pages differently, this page alternates between the \
53 default and even-page header depending on whether it lands on an even or odd page number.",
54 ));
55
56 document.save_to_file(&path)?;
57 println!("Wrote {}", path.display());
58 Ok(())
59}13fn main() -> office_toolkit::Result<()> {
14 let path = output_path("docx_styles_and_lists.docx");
15
16 let heading_style = Style::new("Heading1", "Heading 1", StyleKind::Paragraph)
17 .with_bold(true)
18 .with_font_size(32);
19 let emphasis_style = Style::new("StrongEmphasis", "Strong Emphasis", StyleKind::Character)
20 .with_bold(true)
21 .with_color("C00000");
22
23 let bulleted = NumberingDefinition::bullet(1);
24 let numbered = NumberingDefinition::decimal(2);
25 let custom = NumberingDefinition::new(
26 3,
27 vec![
28 ListLevel::new(NumberFormat::UpperRoman, "%1.", 720, 360),
29 ListLevel::new(NumberFormat::LowerLetter, "%2)", 1440, 360),
30 ],
31 );
32
33 let document = Document::new()
34 .with_style(heading_style)
35 .with_style(emphasis_style)
36 .with_numbering_definition(bulleted)
37 .with_numbering_definition(numbered)
38 .with_numbering_definition(custom)
39 .with_paragraph(heading("Named paragraph and character styles", false))
40 .with_paragraph(
41 Paragraph::with_text("This paragraph uses the Heading 1 style.")
42 .with_style_id("Heading1"),
43 )
44 .with_paragraph(
45 Paragraph::new()
46 .with_run(Run::new("Plain text, then "))
47 .with_run(Run::new("some strongly emphasized text").with_style_id("StrongEmphasis"))
48 .with_run(Run::new(", then plain text again.")),
49 )
50 .with_paragraph(heading("Bulleted list", true))
51 .with_paragraph(Paragraph::with_text("First item").with_numbering(1, 0))
52 .with_paragraph(Paragraph::with_text("Second item").with_numbering(1, 0))
53 .with_paragraph(Paragraph::with_text("A sub-item, one level deeper").with_numbering(1, 1))
54 .with_paragraph(heading("Numbered list", true))
55 .with_paragraph(Paragraph::with_text("First step").with_numbering(2, 0))
56 .with_paragraph(Paragraph::with_text("Second step").with_numbering(2, 0))
57 .with_paragraph(
58 Paragraph::with_text("A sub-step, cumulatively numbered").with_numbering(2, 1),
59 )
60 .with_paragraph(heading(
61 "Custom multi-level list (roman numerals, then letters)",
62 true,
63 ))
64 .with_paragraph(Paragraph::with_text("First top-level item").with_numbering(3, 0))
65 .with_paragraph(Paragraph::with_text("A lettered sub-item").with_numbering(3, 1))
66 .with_paragraph(Paragraph::with_text("Second top-level item").with_numbering(3, 0));
67
68 document.save_to_file(&path)?;
69 println!("Wrote {}", path.display());
70 Ok(())
71}Sourcepub fn with_paragraph(self, paragraph: Paragraph) -> Document
pub fn with_paragraph(self, paragraph: Paragraph) -> Document
Appends a paragraph block and returns the document for chaining.
Examples found in repository?
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}More examples
18fn main() -> office_toolkit::Result<()> {
19 let path = output_path("docx_images_and_charts.docx");
20 let image_bytes = std::fs::read(image_fixture_path())?;
21
22 // 2 inches wide, 1.5 inches tall (914,400 EMU per inch).
23 let image = Image::new(image_bytes, ImageFormat::Png, 1_828_800, 1_371_600)
24 .with_description("Project test image");
25 let chart = EmbeddedChart::new(sample_chart_space(), 4_572_000, 2_743_200)
26 .with_name("Quarterly revenue");
27
28 let document = Document::new()
29 .with_paragraph(heading("An inline image", false))
30 .with_paragraph(Paragraph::new().with_run(Run::with_image(image)))
31 .with_paragraph(heading("An embedded bar chart", true))
32 .with_paragraph(Paragraph::new().with_run(Run::with_chart(chart)));
33
34 document.save_to_file(&path)?;
35 println!("Wrote {}", path.display());
36 Ok(())
37}14fn main() -> office_toolkit::Result<()> {
15 let default_theme_document = Document::new()
16 .with_theme(Theme::office_default())
17 .with_paragraph(Paragraph::with_text("Office's built-in default theme."))
18 .with_paragraph(Paragraph::with_text(
19 "Cambria for headings, Calibri for body text, the classic Office palette.",
20 ));
21 let default_path = output_path("docx_theme_default.docx");
22 default_theme_document.save_to_file(&default_path)?;
23 println!("Wrote {}", default_path.display());
24
25 // A custom, branded theme: a dark navy/orange palette and a different
26 // heading/body font pairing.
27 let custom_colors = ColorScheme::new(
28 "1B1B1B", "FFFFFF", "0A2540", "F5F5F5", "0A2540", "E8622C", "2E86AB", "6FB98F", "F4A259",
29 "8E4585", "1155CC", "6B3FA0",
30 );
31 let custom_fonts = FontScheme::new("Georgia", "Verdana");
32 let custom_theme_document = Document::new()
33 .with_theme(Theme::new("Custom Brand", custom_colors, custom_fonts))
34 .with_paragraph(Paragraph::with_text("A custom, branded theme."))
35 .with_paragraph(Paragraph::with_text(
36 "Georgia for headings, Verdana for body text, a navy/orange palette.",
37 ));
38 let custom_path = output_path("docx_theme_custom.docx");
39 custom_theme_document.save_to_file(&custom_path)?;
40 println!("Wrote {}", custom_path.display());
41
42 Ok(())
43}16fn main() -> office_toolkit::Result<()> {
17 let properties = DocumentProperties::new()
18 .with_title("Quarterly Report")
19 .with_subject("Q3 results")
20 .with_creator("Jane Doe")
21 .with_keywords("finance, quarterly, report")
22 .with_description("An example document showing document properties.")
23 .with_category("Finance")
24 .with_content_status("Draft");
25 let extended_properties = ExtendedProperties::new()
26 .with_company("Acme Corp.")
27 .with_manager("Jane Manager");
28
29 let metadata_document = Document::new()
30 .with_properties(properties)
31 .with_extended_properties(extended_properties)
32 .with_custom_property("ProjectCode", CustomPropertyValue::Text("Q3-2026".to_string()))
33 .with_custom_property("Budget", CustomPropertyValue::Number(125_000.0))
34 .with_custom_property("Approved", CustomPropertyValue::Bool(false))
35 .with_custom_property("RevisionCount", CustomPropertyValue::Int(3))
36 .with_track_changes(true)
37 .with_paragraph(Paragraph::with_text(
38 "This document carries standard properties (title/author/subject/...), four custom properties, \
39 and has track changes turned on — check File > Info in Word to see them.",
40 ));
41 let metadata_path = output_path("docx_metadata.docx");
42 metadata_document.save_to_file(&metadata_path)?;
43 println!("Wrote {}", metadata_path.display());
44
45 let protected_document = Document::new()
46 .with_protection(ProtectionKind::ReadOnly)
47 .with_paragraph(Paragraph::with_text(
48 "This document is protected as read-only — Word will ask for a password before allowing edits.",
49 ));
50 let protected_path = output_path("docx_protected.docx");
51 protected_document.save_to_file(&protected_path)?;
52 println!("Wrote {}", protected_path.display());
53
54 Ok(())
55}15fn main() -> office_toolkit::Result<()> {
16 let path = output_path("docx_page_layout.docx");
17
18 let page_setup = PageSetup::new()
19 .with_size_twips(16_838, 11_906) // A4 landscape, in twentieths of a point
20 .with_orientation(Orientation::Landscape)
21 .with_margins_twips(1_440, 1_440, 1_800, 1_800) // top, bottom, left, right
22 .with_header_footer_margins_twips(720, 720)
23 .with_gutter_twips(0)
24 .with_columns(2);
25
26 let default_header =
27 HeaderFooter::new().with_paragraph(Paragraph::with_text("Default header — every page"));
28 let default_footer =
29 HeaderFooter::new().with_paragraph(Paragraph::with_text("Default footer — every page"));
30 let first_header = HeaderFooter::new()
31 .with_paragraph(Paragraph::with_text("First-page header — cover page only"));
32 let even_header = HeaderFooter::new().with_paragraph(Paragraph::with_text("Even-page header"));
33
34 let document = Document::new()
35 .with_page_setup(page_setup)
36 .with_header(default_header)
37 .with_footer(default_footer)
38 .with_header_first(first_header)
39 .with_header_even(even_header)
40 .with_paragraph(heading("Page setup: A4 landscape, custom margins, two columns", false))
41 .with_paragraph(Paragraph::with_text(
42 "This document is landscape A4, with wider left/right margins than top/bottom, and its body text \
43 flows in two columns. Look at the page in Word's Layout view to see the effect.",
44 ))
45 .with_paragraph(heading("Headers and footers", true))
46 .with_paragraph(Paragraph::with_text(
47 "Page 1 (this page) uses the first-page header, since \"different first page\" headers are set. \
48 Every other page uses the default header shown above, and every page uses the default footer.",
49 ))
50 .with_paragraph(heading("A third page, to see the default header again", true))
51 .with_paragraph(Paragraph::with_text(
52 "If Word is configured to show even/odd pages differently, this page alternates between the \
53 default and even-page header depending on whether it lands on an even or odd page number.",
54 ));
55
56 document.save_to_file(&path)?;
57 println!("Wrote {}", path.display());
58 Ok(())
59}13fn main() -> office_toolkit::Result<()> {
14 let path = output_path("docx_styles_and_lists.docx");
15
16 let heading_style = Style::new("Heading1", "Heading 1", StyleKind::Paragraph)
17 .with_bold(true)
18 .with_font_size(32);
19 let emphasis_style = Style::new("StrongEmphasis", "Strong Emphasis", StyleKind::Character)
20 .with_bold(true)
21 .with_color("C00000");
22
23 let bulleted = NumberingDefinition::bullet(1);
24 let numbered = NumberingDefinition::decimal(2);
25 let custom = NumberingDefinition::new(
26 3,
27 vec![
28 ListLevel::new(NumberFormat::UpperRoman, "%1.", 720, 360),
29 ListLevel::new(NumberFormat::LowerLetter, "%2)", 1440, 360),
30 ],
31 );
32
33 let document = Document::new()
34 .with_style(heading_style)
35 .with_style(emphasis_style)
36 .with_numbering_definition(bulleted)
37 .with_numbering_definition(numbered)
38 .with_numbering_definition(custom)
39 .with_paragraph(heading("Named paragraph and character styles", false))
40 .with_paragraph(
41 Paragraph::with_text("This paragraph uses the Heading 1 style.")
42 .with_style_id("Heading1"),
43 )
44 .with_paragraph(
45 Paragraph::new()
46 .with_run(Run::new("Plain text, then "))
47 .with_run(Run::new("some strongly emphasized text").with_style_id("StrongEmphasis"))
48 .with_run(Run::new(", then plain text again.")),
49 )
50 .with_paragraph(heading("Bulleted list", true))
51 .with_paragraph(Paragraph::with_text("First item").with_numbering(1, 0))
52 .with_paragraph(Paragraph::with_text("Second item").with_numbering(1, 0))
53 .with_paragraph(Paragraph::with_text("A sub-item, one level deeper").with_numbering(1, 1))
54 .with_paragraph(heading("Numbered list", true))
55 .with_paragraph(Paragraph::with_text("First step").with_numbering(2, 0))
56 .with_paragraph(Paragraph::with_text("Second step").with_numbering(2, 0))
57 .with_paragraph(
58 Paragraph::with_text("A sub-step, cumulatively numbered").with_numbering(2, 1),
59 )
60 .with_paragraph(heading(
61 "Custom multi-level list (roman numerals, then letters)",
62 true,
63 ))
64 .with_paragraph(Paragraph::with_text("First top-level item").with_numbering(3, 0))
65 .with_paragraph(Paragraph::with_text("A lettered sub-item").with_numbering(3, 1))
66 .with_paragraph(Paragraph::with_text("Second top-level item").with_numbering(3, 0));
67
68 document.save_to_file(&path)?;
69 println!("Wrote {}", path.display());
70 Ok(())
71}Sourcepub fn with_table(self, table: Table) -> Document
pub fn with_table(self, table: Table) -> Document
Appends a table block and returns the document for chaining.
Examples found in repository?
13fn main() -> office_toolkit::Result<()> {
14 let path = output_path("docx_tables.docx");
15
16 let plain_table = Table::new()
17 .with_row(
18 TableRow::new()
19 .with_cell(TableCell::with_text("Name"))
20 .with_cell(TableCell::with_text("Score")),
21 )
22 .with_row(
23 TableRow::new()
24 .with_cell(TableCell::with_text("Alice"))
25 .with_cell(TableCell::with_text("92")),
26 )
27 .with_row(
28 TableRow::new()
29 .with_cell(TableCell::with_text("Bob"))
30 .with_cell(TableCell::with_text("87")),
31 );
32
33 let merged_table = Table::new()
34 .with_row(
35 TableRow::new()
36 .with_repeat_as_header_row(true)
37 .with_cell(TableCell::with_text("Quarterly report").with_horizontal_span(3)),
38 )
39 .with_row(
40 TableRow::new()
41 .with_cell(
42 TableCell::with_text("Region").with_vertical_merge(VerticalMerge::Restart),
43 )
44 .with_cell(TableCell::with_text("Q1"))
45 .with_cell(TableCell::with_text("Q2")),
46 )
47 .with_row(
48 TableRow::new()
49 .with_cell(TableCell::new().with_vertical_merge(VerticalMerge::Continue))
50 .with_cell(TableCell::with_text("1,200"))
51 .with_cell(TableCell::with_text("1,350")),
52 );
53
54 let styled_table = Table::new()
55 .with_column_widths(vec![3_000, 3_000, 3_000])
56 .with_border_color("2E74B5")
57 .with_indent_twips(360)
58 .with_row(
59 TableRow::new()
60 .with_height_twips(500)
61 .with_cell(TableCell::with_text("Header A").with_shading_color("D9E2F3"))
62 .with_cell(TableCell::with_text("Header B").with_shading_color("D9E2F3"))
63 .with_cell(TableCell::with_text("Header C").with_shading_color("D9E2F3")),
64 )
65 .with_row(
66 TableRow::new()
67 .with_cant_split(true)
68 .with_cell(TableCell::with_text("1").with_border(true))
69 .with_cell(TableCell::with_text("2").with_border(true))
70 .with_cell(TableCell::with_text("3").with_border(true)),
71 );
72
73 let document = Document::new()
74 .with_paragraph(heading("A plain table", false))
75 .with_table(plain_table)
76 .with_paragraph(heading(
77 "Merged cells: a spanning header row and a vertically merged column",
78 true,
79 ))
80 .with_table(merged_table)
81 .with_paragraph(heading(
82 "Column widths, border color, shading and indentation",
83 true,
84 ))
85 .with_table(styled_table);
86
87 document.save_to_file(&path)?;
88 println!("Wrote {}", path.display());
89 Ok(())
90}Sourcepub fn add_paragraph(&mut self, text: impl Into<String>) -> &mut Paragraph
pub fn add_paragraph(&mut self, text: impl Into<String>) -> &mut Paragraph
Appends a paragraph with the given text and returns a mutable reference to it, for further
in-place styling (e.g. document.add_paragraph("..").with_alignment(..) isn’t possible
since with_* consumes self — reach for paragraph.alignment =.. or
paragraph.runs.push(..) on the returned reference instead). A &mut self counterpart to
Self::with_paragraph, for the common case of building a document by appending to it in a
loop, where the consuming builder would otherwise force a document = document.with_paragraph(..) reassignment on every iteration.
Sourcepub fn paragraphs(&self) -> impl Iterator<Item = &Paragraph>
pub fn paragraphs(&self) -> impl Iterator<Item = &Paragraph>
Iterates over the document’s paragraphs only, skipping tables. A convenience for the common
case of not caring about tables; use blocks directly to see paragraphs and tables in their
actual reading order.
Examples found in repository?
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}Sourcepub fn tables(&self) -> impl Iterator<Item = &Table>
pub fn tables(&self) -> impl Iterator<Item = &Table>
Iterates over the document’s tables only, skipping paragraphs.
Sourcepub fn with_header(self, header: HeaderFooter) -> Document
pub fn with_header(self, header: HeaderFooter) -> Document
Sets the document’s default header and returns it for chaining.
Examples found in repository?
15fn main() -> office_toolkit::Result<()> {
16 let path = output_path("docx_page_layout.docx");
17
18 let page_setup = PageSetup::new()
19 .with_size_twips(16_838, 11_906) // A4 landscape, in twentieths of a point
20 .with_orientation(Orientation::Landscape)
21 .with_margins_twips(1_440, 1_440, 1_800, 1_800) // top, bottom, left, right
22 .with_header_footer_margins_twips(720, 720)
23 .with_gutter_twips(0)
24 .with_columns(2);
25
26 let default_header =
27 HeaderFooter::new().with_paragraph(Paragraph::with_text("Default header — every page"));
28 let default_footer =
29 HeaderFooter::new().with_paragraph(Paragraph::with_text("Default footer — every page"));
30 let first_header = HeaderFooter::new()
31 .with_paragraph(Paragraph::with_text("First-page header — cover page only"));
32 let even_header = HeaderFooter::new().with_paragraph(Paragraph::with_text("Even-page header"));
33
34 let document = Document::new()
35 .with_page_setup(page_setup)
36 .with_header(default_header)
37 .with_footer(default_footer)
38 .with_header_first(first_header)
39 .with_header_even(even_header)
40 .with_paragraph(heading("Page setup: A4 landscape, custom margins, two columns", false))
41 .with_paragraph(Paragraph::with_text(
42 "This document is landscape A4, with wider left/right margins than top/bottom, and its body text \
43 flows in two columns. Look at the page in Word's Layout view to see the effect.",
44 ))
45 .with_paragraph(heading("Headers and footers", true))
46 .with_paragraph(Paragraph::with_text(
47 "Page 1 (this page) uses the first-page header, since \"different first page\" headers are set. \
48 Every other page uses the default header shown above, and every page uses the default footer.",
49 ))
50 .with_paragraph(heading("A third page, to see the default header again", true))
51 .with_paragraph(Paragraph::with_text(
52 "If Word is configured to show even/odd pages differently, this page alternates between the \
53 default and even-page header depending on whether it lands on an even or odd page number.",
54 ));
55
56 document.save_to_file(&path)?;
57 println!("Wrote {}", path.display());
58 Ok(())
59}Sets the document’s default footer and returns it for chaining.
Examples found in repository?
15fn main() -> office_toolkit::Result<()> {
16 let path = output_path("docx_page_layout.docx");
17
18 let page_setup = PageSetup::new()
19 .with_size_twips(16_838, 11_906) // A4 landscape, in twentieths of a point
20 .with_orientation(Orientation::Landscape)
21 .with_margins_twips(1_440, 1_440, 1_800, 1_800) // top, bottom, left, right
22 .with_header_footer_margins_twips(720, 720)
23 .with_gutter_twips(0)
24 .with_columns(2);
25
26 let default_header =
27 HeaderFooter::new().with_paragraph(Paragraph::with_text("Default header — every page"));
28 let default_footer =
29 HeaderFooter::new().with_paragraph(Paragraph::with_text("Default footer — every page"));
30 let first_header = HeaderFooter::new()
31 .with_paragraph(Paragraph::with_text("First-page header — cover page only"));
32 let even_header = HeaderFooter::new().with_paragraph(Paragraph::with_text("Even-page header"));
33
34 let document = Document::new()
35 .with_page_setup(page_setup)
36 .with_header(default_header)
37 .with_footer(default_footer)
38 .with_header_first(first_header)
39 .with_header_even(even_header)
40 .with_paragraph(heading("Page setup: A4 landscape, custom margins, two columns", false))
41 .with_paragraph(Paragraph::with_text(
42 "This document is landscape A4, with wider left/right margins than top/bottom, and its body text \
43 flows in two columns. Look at the page in Word's Layout view to see the effect.",
44 ))
45 .with_paragraph(heading("Headers and footers", true))
46 .with_paragraph(Paragraph::with_text(
47 "Page 1 (this page) uses the first-page header, since \"different first page\" headers are set. \
48 Every other page uses the default header shown above, and every page uses the default footer.",
49 ))
50 .with_paragraph(heading("A third page, to see the default header again", true))
51 .with_paragraph(Paragraph::with_text(
52 "If Word is configured to show even/odd pages differently, this page alternates between the \
53 default and even-page header depending on whether it lands on an even or odd page number.",
54 ));
55
56 document.save_to_file(&path)?;
57 println!("Wrote {}", path.display());
58 Ok(())
59}Sourcepub fn with_header_first(self, header: HeaderFooter) -> Document
pub fn with_header_first(self, header: HeaderFooter) -> Document
Sets the document’s first-page header and returns it for chaining. See header_first’s doc
comment.
Examples found in repository?
15fn main() -> office_toolkit::Result<()> {
16 let path = output_path("docx_page_layout.docx");
17
18 let page_setup = PageSetup::new()
19 .with_size_twips(16_838, 11_906) // A4 landscape, in twentieths of a point
20 .with_orientation(Orientation::Landscape)
21 .with_margins_twips(1_440, 1_440, 1_800, 1_800) // top, bottom, left, right
22 .with_header_footer_margins_twips(720, 720)
23 .with_gutter_twips(0)
24 .with_columns(2);
25
26 let default_header =
27 HeaderFooter::new().with_paragraph(Paragraph::with_text("Default header — every page"));
28 let default_footer =
29 HeaderFooter::new().with_paragraph(Paragraph::with_text("Default footer — every page"));
30 let first_header = HeaderFooter::new()
31 .with_paragraph(Paragraph::with_text("First-page header — cover page only"));
32 let even_header = HeaderFooter::new().with_paragraph(Paragraph::with_text("Even-page header"));
33
34 let document = Document::new()
35 .with_page_setup(page_setup)
36 .with_header(default_header)
37 .with_footer(default_footer)
38 .with_header_first(first_header)
39 .with_header_even(even_header)
40 .with_paragraph(heading("Page setup: A4 landscape, custom margins, two columns", false))
41 .with_paragraph(Paragraph::with_text(
42 "This document is landscape A4, with wider left/right margins than top/bottom, and its body text \
43 flows in two columns. Look at the page in Word's Layout view to see the effect.",
44 ))
45 .with_paragraph(heading("Headers and footers", true))
46 .with_paragraph(Paragraph::with_text(
47 "Page 1 (this page) uses the first-page header, since \"different first page\" headers are set. \
48 Every other page uses the default header shown above, and every page uses the default footer.",
49 ))
50 .with_paragraph(heading("A third page, to see the default header again", true))
51 .with_paragraph(Paragraph::with_text(
52 "If Word is configured to show even/odd pages differently, this page alternates between the \
53 default and even-page header depending on whether it lands on an even or odd page number.",
54 ));
55
56 document.save_to_file(&path)?;
57 println!("Wrote {}", path.display());
58 Ok(())
59}Sets the document’s first-page footer and returns it for chaining.
Sourcepub fn with_header_even(self, header: HeaderFooter) -> Document
pub fn with_header_even(self, header: HeaderFooter) -> Document
Sets the document’s even-page header and returns it for chaining. See header_even’s doc
comment.
Examples found in repository?
15fn main() -> office_toolkit::Result<()> {
16 let path = output_path("docx_page_layout.docx");
17
18 let page_setup = PageSetup::new()
19 .with_size_twips(16_838, 11_906) // A4 landscape, in twentieths of a point
20 .with_orientation(Orientation::Landscape)
21 .with_margins_twips(1_440, 1_440, 1_800, 1_800) // top, bottom, left, right
22 .with_header_footer_margins_twips(720, 720)
23 .with_gutter_twips(0)
24 .with_columns(2);
25
26 let default_header =
27 HeaderFooter::new().with_paragraph(Paragraph::with_text("Default header — every page"));
28 let default_footer =
29 HeaderFooter::new().with_paragraph(Paragraph::with_text("Default footer — every page"));
30 let first_header = HeaderFooter::new()
31 .with_paragraph(Paragraph::with_text("First-page header — cover page only"));
32 let even_header = HeaderFooter::new().with_paragraph(Paragraph::with_text("Even-page header"));
33
34 let document = Document::new()
35 .with_page_setup(page_setup)
36 .with_header(default_header)
37 .with_footer(default_footer)
38 .with_header_first(first_header)
39 .with_header_even(even_header)
40 .with_paragraph(heading("Page setup: A4 landscape, custom margins, two columns", false))
41 .with_paragraph(Paragraph::with_text(
42 "This document is landscape A4, with wider left/right margins than top/bottom, and its body text \
43 flows in two columns. Look at the page in Word's Layout view to see the effect.",
44 ))
45 .with_paragraph(heading("Headers and footers", true))
46 .with_paragraph(Paragraph::with_text(
47 "Page 1 (this page) uses the first-page header, since \"different first page\" headers are set. \
48 Every other page uses the default header shown above, and every page uses the default footer.",
49 ))
50 .with_paragraph(heading("A third page, to see the default header again", true))
51 .with_paragraph(Paragraph::with_text(
52 "If Word is configured to show even/odd pages differently, this page alternates between the \
53 default and even-page header depending on whether it lands on an even or odd page number.",
54 ));
55
56 document.save_to_file(&path)?;
57 println!("Wrote {}", path.display());
58 Ok(())
59}Sets the document’s even-page footer and returns it for chaining.
Sourcepub fn with_page_setup(self, page_setup: PageSetup) -> Document
pub fn with_page_setup(self, page_setup: PageSetup) -> Document
Sets the document’s page setup and returns it for chaining.
Examples found in repository?
15fn main() -> office_toolkit::Result<()> {
16 let path = output_path("docx_page_layout.docx");
17
18 let page_setup = PageSetup::new()
19 .with_size_twips(16_838, 11_906) // A4 landscape, in twentieths of a point
20 .with_orientation(Orientation::Landscape)
21 .with_margins_twips(1_440, 1_440, 1_800, 1_800) // top, bottom, left, right
22 .with_header_footer_margins_twips(720, 720)
23 .with_gutter_twips(0)
24 .with_columns(2);
25
26 let default_header =
27 HeaderFooter::new().with_paragraph(Paragraph::with_text("Default header — every page"));
28 let default_footer =
29 HeaderFooter::new().with_paragraph(Paragraph::with_text("Default footer — every page"));
30 let first_header = HeaderFooter::new()
31 .with_paragraph(Paragraph::with_text("First-page header — cover page only"));
32 let even_header = HeaderFooter::new().with_paragraph(Paragraph::with_text("Even-page header"));
33
34 let document = Document::new()
35 .with_page_setup(page_setup)
36 .with_header(default_header)
37 .with_footer(default_footer)
38 .with_header_first(first_header)
39 .with_header_even(even_header)
40 .with_paragraph(heading("Page setup: A4 landscape, custom margins, two columns", false))
41 .with_paragraph(Paragraph::with_text(
42 "This document is landscape A4, with wider left/right margins than top/bottom, and its body text \
43 flows in two columns. Look at the page in Word's Layout view to see the effect.",
44 ))
45 .with_paragraph(heading("Headers and footers", true))
46 .with_paragraph(Paragraph::with_text(
47 "Page 1 (this page) uses the first-page header, since \"different first page\" headers are set. \
48 Every other page uses the default header shown above, and every page uses the default footer.",
49 ))
50 .with_paragraph(heading("A third page, to see the default header again", true))
51 .with_paragraph(Paragraph::with_text(
52 "If Word is configured to show even/odd pages differently, this page alternates between the \
53 default and even-page header depending on whether it lands on an even or odd page number.",
54 ));
55
56 document.save_to_file(&path)?;
57 println!("Wrote {}", path.display());
58 Ok(())
59}Sourcepub fn with_style(self, style: Style) -> Document
pub fn with_style(self, style: Style) -> Document
Appends a named style declaration and returns the document for chaining.
Examples found in repository?
13fn main() -> office_toolkit::Result<()> {
14 let path = output_path("docx_styles_and_lists.docx");
15
16 let heading_style = Style::new("Heading1", "Heading 1", StyleKind::Paragraph)
17 .with_bold(true)
18 .with_font_size(32);
19 let emphasis_style = Style::new("StrongEmphasis", "Strong Emphasis", StyleKind::Character)
20 .with_bold(true)
21 .with_color("C00000");
22
23 let bulleted = NumberingDefinition::bullet(1);
24 let numbered = NumberingDefinition::decimal(2);
25 let custom = NumberingDefinition::new(
26 3,
27 vec![
28 ListLevel::new(NumberFormat::UpperRoman, "%1.", 720, 360),
29 ListLevel::new(NumberFormat::LowerLetter, "%2)", 1440, 360),
30 ],
31 );
32
33 let document = Document::new()
34 .with_style(heading_style)
35 .with_style(emphasis_style)
36 .with_numbering_definition(bulleted)
37 .with_numbering_definition(numbered)
38 .with_numbering_definition(custom)
39 .with_paragraph(heading("Named paragraph and character styles", false))
40 .with_paragraph(
41 Paragraph::with_text("This paragraph uses the Heading 1 style.")
42 .with_style_id("Heading1"),
43 )
44 .with_paragraph(
45 Paragraph::new()
46 .with_run(Run::new("Plain text, then "))
47 .with_run(Run::new("some strongly emphasized text").with_style_id("StrongEmphasis"))
48 .with_run(Run::new(", then plain text again.")),
49 )
50 .with_paragraph(heading("Bulleted list", true))
51 .with_paragraph(Paragraph::with_text("First item").with_numbering(1, 0))
52 .with_paragraph(Paragraph::with_text("Second item").with_numbering(1, 0))
53 .with_paragraph(Paragraph::with_text("A sub-item, one level deeper").with_numbering(1, 1))
54 .with_paragraph(heading("Numbered list", true))
55 .with_paragraph(Paragraph::with_text("First step").with_numbering(2, 0))
56 .with_paragraph(Paragraph::with_text("Second step").with_numbering(2, 0))
57 .with_paragraph(
58 Paragraph::with_text("A sub-step, cumulatively numbered").with_numbering(2, 1),
59 )
60 .with_paragraph(heading(
61 "Custom multi-level list (roman numerals, then letters)",
62 true,
63 ))
64 .with_paragraph(Paragraph::with_text("First top-level item").with_numbering(3, 0))
65 .with_paragraph(Paragraph::with_text("A lettered sub-item").with_numbering(3, 1))
66 .with_paragraph(Paragraph::with_text("Second top-level item").with_numbering(3, 0));
67
68 document.save_to_file(&path)?;
69 println!("Wrote {}", path.display());
70 Ok(())
71}Sourcepub fn with_numbering_definition(
self,
definition: NumberingDefinition,
) -> Document
pub fn with_numbering_definition( self, definition: NumberingDefinition, ) -> Document
Appends a numbering (list) definition and returns the document for chaining.
Examples found in repository?
13fn main() -> office_toolkit::Result<()> {
14 let path = output_path("docx_styles_and_lists.docx");
15
16 let heading_style = Style::new("Heading1", "Heading 1", StyleKind::Paragraph)
17 .with_bold(true)
18 .with_font_size(32);
19 let emphasis_style = Style::new("StrongEmphasis", "Strong Emphasis", StyleKind::Character)
20 .with_bold(true)
21 .with_color("C00000");
22
23 let bulleted = NumberingDefinition::bullet(1);
24 let numbered = NumberingDefinition::decimal(2);
25 let custom = NumberingDefinition::new(
26 3,
27 vec![
28 ListLevel::new(NumberFormat::UpperRoman, "%1.", 720, 360),
29 ListLevel::new(NumberFormat::LowerLetter, "%2)", 1440, 360),
30 ],
31 );
32
33 let document = Document::new()
34 .with_style(heading_style)
35 .with_style(emphasis_style)
36 .with_numbering_definition(bulleted)
37 .with_numbering_definition(numbered)
38 .with_numbering_definition(custom)
39 .with_paragraph(heading("Named paragraph and character styles", false))
40 .with_paragraph(
41 Paragraph::with_text("This paragraph uses the Heading 1 style.")
42 .with_style_id("Heading1"),
43 )
44 .with_paragraph(
45 Paragraph::new()
46 .with_run(Run::new("Plain text, then "))
47 .with_run(Run::new("some strongly emphasized text").with_style_id("StrongEmphasis"))
48 .with_run(Run::new(", then plain text again.")),
49 )
50 .with_paragraph(heading("Bulleted list", true))
51 .with_paragraph(Paragraph::with_text("First item").with_numbering(1, 0))
52 .with_paragraph(Paragraph::with_text("Second item").with_numbering(1, 0))
53 .with_paragraph(Paragraph::with_text("A sub-item, one level deeper").with_numbering(1, 1))
54 .with_paragraph(heading("Numbered list", true))
55 .with_paragraph(Paragraph::with_text("First step").with_numbering(2, 0))
56 .with_paragraph(Paragraph::with_text("Second step").with_numbering(2, 0))
57 .with_paragraph(
58 Paragraph::with_text("A sub-step, cumulatively numbered").with_numbering(2, 1),
59 )
60 .with_paragraph(heading(
61 "Custom multi-level list (roman numerals, then letters)",
62 true,
63 ))
64 .with_paragraph(Paragraph::with_text("First top-level item").with_numbering(3, 0))
65 .with_paragraph(Paragraph::with_text("A lettered sub-item").with_numbering(3, 1))
66 .with_paragraph(Paragraph::with_text("Second top-level item").with_numbering(3, 0));
67
68 document.save_to_file(&path)?;
69 println!("Wrote {}", path.display());
70 Ok(())
71}Sourcepub fn with_footnote(self, note: Note) -> Document
pub fn with_footnote(self, note: Note) -> Document
Appends a footnote declaration and returns the document for chaining.
Examples found in repository?
15fn main() -> office_toolkit::Result<()> {
16 let path = output_path("docx_navigation_and_annotations.docx");
17
18 let document =
19 Document::new()
20 .with_paragraph(heading(
21 "Hyperlinks: external, and internal to a bookmark",
22 false,
23 ))
24 .with_paragraph(
25 Paragraph::new()
26 .with_run(Run::new("Visit the ").with_hyperlink(Hyperlink::External(
27 "https://www.rust-lang.org".to_string(),
28 )))
29 .with_run(Run::new("or jump ").with_hyperlink(Hyperlink::External(
30 "https://www.rust-lang.org".to_string(),
31 )))
32 .with_run(
33 Run::new("down to the bookmark")
34 .with_hyperlink(Hyperlink::Internal("Target".to_string())),
35 ),
36 )
37 .with_paragraph(
38 Paragraph::new()
39 .with_run(Run::new("Here is ").with_bookmark(Bookmark::new(0, "Target")))
40 .with_run(
41 Run::new("the bookmarked text.").with_bookmark(Bookmark::new(0, "Target")),
42 ),
43 )
44 .with_paragraph(heading("Comments", true))
45 .with_paragraph(
46 Paragraph::new()
47 .with_run(Run::new("This sentence "))
48 .with_run(Run::new("needs a second look").with_comment(0))
49 .with_run(Run::new(" before it ships.")),
50 )
51 .with_comment(
52 Comment::with_text(0, "Please double-check this claim.")
53 .with_author("Reviewer")
54 .with_initials("RV"),
55 )
56 .with_paragraph(heading("Footnotes and endnotes", true))
57 .with_paragraph(
58 Paragraph::with_text("A claim that needs a footnote")
59 .with_run(Run::with_note_reference(NoteReference::Footnote(1)))
60 .with_run(Run::new(", and another that needs an endnote"))
61 .with_run(Run::with_note_reference(NoteReference::Endnote(1))),
62 )
63 .with_footnote(Note::footnote_with_text(
64 1,
65 "The footnote's own explanatory text.",
66 ))
67 .with_endnote(Note::endnote_with_text(
68 1,
69 "The endnote's own explanatory text.",
70 ))
71 .with_paragraph(heading("A structured document tag (content control)", true))
72 .with_paragraph(Paragraph::with_text("Before the content control:"))
73 .with_structured_document_tag(
74 StructuredDocumentTag::new()
75 .with_id(42)
76 .with_tag("CustomerName")
77 .with_alias("Customer name")
78 .with_paragraph(Paragraph::with_text("Acme Corp.")),
79 );
80
81 document.save_to_file(&path)?;
82 println!("Wrote {}", path.display());
83 Ok(())
84}Sourcepub fn with_endnote(self, note: Note) -> Document
pub fn with_endnote(self, note: Note) -> Document
Appends an endnote declaration and returns the document for chaining.
Examples found in repository?
15fn main() -> office_toolkit::Result<()> {
16 let path = output_path("docx_navigation_and_annotations.docx");
17
18 let document =
19 Document::new()
20 .with_paragraph(heading(
21 "Hyperlinks: external, and internal to a bookmark",
22 false,
23 ))
24 .with_paragraph(
25 Paragraph::new()
26 .with_run(Run::new("Visit the ").with_hyperlink(Hyperlink::External(
27 "https://www.rust-lang.org".to_string(),
28 )))
29 .with_run(Run::new("or jump ").with_hyperlink(Hyperlink::External(
30 "https://www.rust-lang.org".to_string(),
31 )))
32 .with_run(
33 Run::new("down to the bookmark")
34 .with_hyperlink(Hyperlink::Internal("Target".to_string())),
35 ),
36 )
37 .with_paragraph(
38 Paragraph::new()
39 .with_run(Run::new("Here is ").with_bookmark(Bookmark::new(0, "Target")))
40 .with_run(
41 Run::new("the bookmarked text.").with_bookmark(Bookmark::new(0, "Target")),
42 ),
43 )
44 .with_paragraph(heading("Comments", true))
45 .with_paragraph(
46 Paragraph::new()
47 .with_run(Run::new("This sentence "))
48 .with_run(Run::new("needs a second look").with_comment(0))
49 .with_run(Run::new(" before it ships.")),
50 )
51 .with_comment(
52 Comment::with_text(0, "Please double-check this claim.")
53 .with_author("Reviewer")
54 .with_initials("RV"),
55 )
56 .with_paragraph(heading("Footnotes and endnotes", true))
57 .with_paragraph(
58 Paragraph::with_text("A claim that needs a footnote")
59 .with_run(Run::with_note_reference(NoteReference::Footnote(1)))
60 .with_run(Run::new(", and another that needs an endnote"))
61 .with_run(Run::with_note_reference(NoteReference::Endnote(1))),
62 )
63 .with_footnote(Note::footnote_with_text(
64 1,
65 "The footnote's own explanatory text.",
66 ))
67 .with_endnote(Note::endnote_with_text(
68 1,
69 "The endnote's own explanatory text.",
70 ))
71 .with_paragraph(heading("A structured document tag (content control)", true))
72 .with_paragraph(Paragraph::with_text("Before the content control:"))
73 .with_structured_document_tag(
74 StructuredDocumentTag::new()
75 .with_id(42)
76 .with_tag("CustomerName")
77 .with_alias("Customer name")
78 .with_paragraph(Paragraph::with_text("Acme Corp.")),
79 );
80
81 document.save_to_file(&path)?;
82 println!("Wrote {}", path.display());
83 Ok(())
84}Sourcepub fn with_comment(self, comment: Comment) -> Document
pub fn with_comment(self, comment: Comment) -> Document
Appends a comment declaration and returns the document for chaining.
Examples found in repository?
15fn main() -> office_toolkit::Result<()> {
16 let path = output_path("docx_navigation_and_annotations.docx");
17
18 let document =
19 Document::new()
20 .with_paragraph(heading(
21 "Hyperlinks: external, and internal to a bookmark",
22 false,
23 ))
24 .with_paragraph(
25 Paragraph::new()
26 .with_run(Run::new("Visit the ").with_hyperlink(Hyperlink::External(
27 "https://www.rust-lang.org".to_string(),
28 )))
29 .with_run(Run::new("or jump ").with_hyperlink(Hyperlink::External(
30 "https://www.rust-lang.org".to_string(),
31 )))
32 .with_run(
33 Run::new("down to the bookmark")
34 .with_hyperlink(Hyperlink::Internal("Target".to_string())),
35 ),
36 )
37 .with_paragraph(
38 Paragraph::new()
39 .with_run(Run::new("Here is ").with_bookmark(Bookmark::new(0, "Target")))
40 .with_run(
41 Run::new("the bookmarked text.").with_bookmark(Bookmark::new(0, "Target")),
42 ),
43 )
44 .with_paragraph(heading("Comments", true))
45 .with_paragraph(
46 Paragraph::new()
47 .with_run(Run::new("This sentence "))
48 .with_run(Run::new("needs a second look").with_comment(0))
49 .with_run(Run::new(" before it ships.")),
50 )
51 .with_comment(
52 Comment::with_text(0, "Please double-check this claim.")
53 .with_author("Reviewer")
54 .with_initials("RV"),
55 )
56 .with_paragraph(heading("Footnotes and endnotes", true))
57 .with_paragraph(
58 Paragraph::with_text("A claim that needs a footnote")
59 .with_run(Run::with_note_reference(NoteReference::Footnote(1)))
60 .with_run(Run::new(", and another that needs an endnote"))
61 .with_run(Run::with_note_reference(NoteReference::Endnote(1))),
62 )
63 .with_footnote(Note::footnote_with_text(
64 1,
65 "The footnote's own explanatory text.",
66 ))
67 .with_endnote(Note::endnote_with_text(
68 1,
69 "The endnote's own explanatory text.",
70 ))
71 .with_paragraph(heading("A structured document tag (content control)", true))
72 .with_paragraph(Paragraph::with_text("Before the content control:"))
73 .with_structured_document_tag(
74 StructuredDocumentTag::new()
75 .with_id(42)
76 .with_tag("CustomerName")
77 .with_alias("Customer name")
78 .with_paragraph(Paragraph::with_text("Acme Corp.")),
79 );
80
81 document.save_to_file(&path)?;
82 println!("Wrote {}", path.display());
83 Ok(())
84}Sourcepub fn with_structured_document_tag(
self,
sdt: StructuredDocumentTag,
) -> Document
pub fn with_structured_document_tag( self, sdt: StructuredDocumentTag, ) -> Document
Appends a structured document tag block and returns the document for chaining.
Examples found in repository?
15fn main() -> office_toolkit::Result<()> {
16 let path = output_path("docx_navigation_and_annotations.docx");
17
18 let document =
19 Document::new()
20 .with_paragraph(heading(
21 "Hyperlinks: external, and internal to a bookmark",
22 false,
23 ))
24 .with_paragraph(
25 Paragraph::new()
26 .with_run(Run::new("Visit the ").with_hyperlink(Hyperlink::External(
27 "https://www.rust-lang.org".to_string(),
28 )))
29 .with_run(Run::new("or jump ").with_hyperlink(Hyperlink::External(
30 "https://www.rust-lang.org".to_string(),
31 )))
32 .with_run(
33 Run::new("down to the bookmark")
34 .with_hyperlink(Hyperlink::Internal("Target".to_string())),
35 ),
36 )
37 .with_paragraph(
38 Paragraph::new()
39 .with_run(Run::new("Here is ").with_bookmark(Bookmark::new(0, "Target")))
40 .with_run(
41 Run::new("the bookmarked text.").with_bookmark(Bookmark::new(0, "Target")),
42 ),
43 )
44 .with_paragraph(heading("Comments", true))
45 .with_paragraph(
46 Paragraph::new()
47 .with_run(Run::new("This sentence "))
48 .with_run(Run::new("needs a second look").with_comment(0))
49 .with_run(Run::new(" before it ships.")),
50 )
51 .with_comment(
52 Comment::with_text(0, "Please double-check this claim.")
53 .with_author("Reviewer")
54 .with_initials("RV"),
55 )
56 .with_paragraph(heading("Footnotes and endnotes", true))
57 .with_paragraph(
58 Paragraph::with_text("A claim that needs a footnote")
59 .with_run(Run::with_note_reference(NoteReference::Footnote(1)))
60 .with_run(Run::new(", and another that needs an endnote"))
61 .with_run(Run::with_note_reference(NoteReference::Endnote(1))),
62 )
63 .with_footnote(Note::footnote_with_text(
64 1,
65 "The footnote's own explanatory text.",
66 ))
67 .with_endnote(Note::endnote_with_text(
68 1,
69 "The endnote's own explanatory text.",
70 ))
71 .with_paragraph(heading("A structured document tag (content control)", true))
72 .with_paragraph(Paragraph::with_text("Before the content control:"))
73 .with_structured_document_tag(
74 StructuredDocumentTag::new()
75 .with_id(42)
76 .with_tag("CustomerName")
77 .with_alias("Customer name")
78 .with_paragraph(Paragraph::with_text("Acme Corp.")),
79 );
80
81 document.save_to_file(&path)?;
82 println!("Wrote {}", path.display());
83 Ok(())
84}Sourcepub fn with_theme(self, theme: Theme) -> Document
pub fn with_theme(self, theme: Theme) -> Document
Sets the document’s theme and returns it for chaining.
Examples found in repository?
14fn main() -> office_toolkit::Result<()> {
15 let default_theme_document = Document::new()
16 .with_theme(Theme::office_default())
17 .with_paragraph(Paragraph::with_text("Office's built-in default theme."))
18 .with_paragraph(Paragraph::with_text(
19 "Cambria for headings, Calibri for body text, the classic Office palette.",
20 ));
21 let default_path = output_path("docx_theme_default.docx");
22 default_theme_document.save_to_file(&default_path)?;
23 println!("Wrote {}", default_path.display());
24
25 // A custom, branded theme: a dark navy/orange palette and a different
26 // heading/body font pairing.
27 let custom_colors = ColorScheme::new(
28 "1B1B1B", "FFFFFF", "0A2540", "F5F5F5", "0A2540", "E8622C", "2E86AB", "6FB98F", "F4A259",
29 "8E4585", "1155CC", "6B3FA0",
30 );
31 let custom_fonts = FontScheme::new("Georgia", "Verdana");
32 let custom_theme_document = Document::new()
33 .with_theme(Theme::new("Custom Brand", custom_colors, custom_fonts))
34 .with_paragraph(Paragraph::with_text("A custom, branded theme."))
35 .with_paragraph(Paragraph::with_text(
36 "Georgia for headings, Verdana for body text, a navy/orange palette.",
37 ));
38 let custom_path = output_path("docx_theme_custom.docx");
39 custom_theme_document.save_to_file(&custom_path)?;
40 println!("Wrote {}", custom_path.display());
41
42 Ok(())
43}Sourcepub fn with_track_changes(self, track_changes: bool) -> Document
pub fn with_track_changes(self, track_changes: bool) -> Document
Sets whether Word should track changes made to this document from now on and returns it for
chaining. See track_changes’s doc comment.
Examples found in repository?
16fn main() -> office_toolkit::Result<()> {
17 let properties = DocumentProperties::new()
18 .with_title("Quarterly Report")
19 .with_subject("Q3 results")
20 .with_creator("Jane Doe")
21 .with_keywords("finance, quarterly, report")
22 .with_description("An example document showing document properties.")
23 .with_category("Finance")
24 .with_content_status("Draft");
25 let extended_properties = ExtendedProperties::new()
26 .with_company("Acme Corp.")
27 .with_manager("Jane Manager");
28
29 let metadata_document = Document::new()
30 .with_properties(properties)
31 .with_extended_properties(extended_properties)
32 .with_custom_property("ProjectCode", CustomPropertyValue::Text("Q3-2026".to_string()))
33 .with_custom_property("Budget", CustomPropertyValue::Number(125_000.0))
34 .with_custom_property("Approved", CustomPropertyValue::Bool(false))
35 .with_custom_property("RevisionCount", CustomPropertyValue::Int(3))
36 .with_track_changes(true)
37 .with_paragraph(Paragraph::with_text(
38 "This document carries standard properties (title/author/subject/...), four custom properties, \
39 and has track changes turned on — check File > Info in Word to see them.",
40 ));
41 let metadata_path = output_path("docx_metadata.docx");
42 metadata_document.save_to_file(&metadata_path)?;
43 println!("Wrote {}", metadata_path.display());
44
45 let protected_document = Document::new()
46 .with_protection(ProtectionKind::ReadOnly)
47 .with_paragraph(Paragraph::with_text(
48 "This document is protected as read-only — Word will ask for a password before allowing edits.",
49 ));
50 let protected_path = output_path("docx_protected.docx");
51 protected_document.save_to_file(&protected_path)?;
52 println!("Wrote {}", protected_path.display());
53
54 Ok(())
55}Sourcepub fn with_properties(self, properties: DocumentProperties) -> Document
pub fn with_properties(self, properties: DocumentProperties) -> Document
Sets the document’s core properties (title, author, etc.) and returns it for chaining. See
DocumentProperties’s doc comment.
Examples found in repository?
16fn main() -> office_toolkit::Result<()> {
17 let properties = DocumentProperties::new()
18 .with_title("Quarterly Report")
19 .with_subject("Q3 results")
20 .with_creator("Jane Doe")
21 .with_keywords("finance, quarterly, report")
22 .with_description("An example document showing document properties.")
23 .with_category("Finance")
24 .with_content_status("Draft");
25 let extended_properties = ExtendedProperties::new()
26 .with_company("Acme Corp.")
27 .with_manager("Jane Manager");
28
29 let metadata_document = Document::new()
30 .with_properties(properties)
31 .with_extended_properties(extended_properties)
32 .with_custom_property("ProjectCode", CustomPropertyValue::Text("Q3-2026".to_string()))
33 .with_custom_property("Budget", CustomPropertyValue::Number(125_000.0))
34 .with_custom_property("Approved", CustomPropertyValue::Bool(false))
35 .with_custom_property("RevisionCount", CustomPropertyValue::Int(3))
36 .with_track_changes(true)
37 .with_paragraph(Paragraph::with_text(
38 "This document carries standard properties (title/author/subject/...), four custom properties, \
39 and has track changes turned on — check File > Info in Word to see them.",
40 ));
41 let metadata_path = output_path("docx_metadata.docx");
42 metadata_document.save_to_file(&metadata_path)?;
43 println!("Wrote {}", metadata_path.display());
44
45 let protected_document = Document::new()
46 .with_protection(ProtectionKind::ReadOnly)
47 .with_paragraph(Paragraph::with_text(
48 "This document is protected as read-only — Word will ask for a password before allowing edits.",
49 ));
50 let protected_path = output_path("docx_protected.docx");
51 protected_document.save_to_file(&protected_path)?;
52 println!("Wrote {}", protected_path.display());
53
54 Ok(())
55}Sourcepub fn with_protection(self, protection: ProtectionKind) -> Document
pub fn with_protection(self, protection: ProtectionKind) -> Document
Sets which editing restrictions are enforced on the document and returns it for chaining.
See ProtectionKind’s doc comment.
Examples found in repository?
16fn main() -> office_toolkit::Result<()> {
17 let properties = DocumentProperties::new()
18 .with_title("Quarterly Report")
19 .with_subject("Q3 results")
20 .with_creator("Jane Doe")
21 .with_keywords("finance, quarterly, report")
22 .with_description("An example document showing document properties.")
23 .with_category("Finance")
24 .with_content_status("Draft");
25 let extended_properties = ExtendedProperties::new()
26 .with_company("Acme Corp.")
27 .with_manager("Jane Manager");
28
29 let metadata_document = Document::new()
30 .with_properties(properties)
31 .with_extended_properties(extended_properties)
32 .with_custom_property("ProjectCode", CustomPropertyValue::Text("Q3-2026".to_string()))
33 .with_custom_property("Budget", CustomPropertyValue::Number(125_000.0))
34 .with_custom_property("Approved", CustomPropertyValue::Bool(false))
35 .with_custom_property("RevisionCount", CustomPropertyValue::Int(3))
36 .with_track_changes(true)
37 .with_paragraph(Paragraph::with_text(
38 "This document carries standard properties (title/author/subject/...), four custom properties, \
39 and has track changes turned on — check File > Info in Word to see them.",
40 ));
41 let metadata_path = output_path("docx_metadata.docx");
42 metadata_document.save_to_file(&metadata_path)?;
43 println!("Wrote {}", metadata_path.display());
44
45 let protected_document = Document::new()
46 .with_protection(ProtectionKind::ReadOnly)
47 .with_paragraph(Paragraph::with_text(
48 "This document is protected as read-only — Word will ask for a password before allowing edits.",
49 ));
50 let protected_path = output_path("docx_protected.docx");
51 protected_document.save_to_file(&protected_path)?;
52 println!("Wrote {}", protected_path.display());
53
54 Ok(())
55}Sourcepub fn with_extended_properties(
self,
extended_properties: ExtendedProperties,
) -> Document
pub fn with_extended_properties( self, extended_properties: ExtendedProperties, ) -> Document
Sets the document’s extended properties (company/manager) and returns it for chaining. See
ExtendedProperties’s doc comment.
Examples found in repository?
16fn main() -> office_toolkit::Result<()> {
17 let properties = DocumentProperties::new()
18 .with_title("Quarterly Report")
19 .with_subject("Q3 results")
20 .with_creator("Jane Doe")
21 .with_keywords("finance, quarterly, report")
22 .with_description("An example document showing document properties.")
23 .with_category("Finance")
24 .with_content_status("Draft");
25 let extended_properties = ExtendedProperties::new()
26 .with_company("Acme Corp.")
27 .with_manager("Jane Manager");
28
29 let metadata_document = Document::new()
30 .with_properties(properties)
31 .with_extended_properties(extended_properties)
32 .with_custom_property("ProjectCode", CustomPropertyValue::Text("Q3-2026".to_string()))
33 .with_custom_property("Budget", CustomPropertyValue::Number(125_000.0))
34 .with_custom_property("Approved", CustomPropertyValue::Bool(false))
35 .with_custom_property("RevisionCount", CustomPropertyValue::Int(3))
36 .with_track_changes(true)
37 .with_paragraph(Paragraph::with_text(
38 "This document carries standard properties (title/author/subject/...), four custom properties, \
39 and has track changes turned on — check File > Info in Word to see them.",
40 ));
41 let metadata_path = output_path("docx_metadata.docx");
42 metadata_document.save_to_file(&metadata_path)?;
43 println!("Wrote {}", metadata_path.display());
44
45 let protected_document = Document::new()
46 .with_protection(ProtectionKind::ReadOnly)
47 .with_paragraph(Paragraph::with_text(
48 "This document is protected as read-only — Word will ask for a password before allowing edits.",
49 ));
50 let protected_path = output_path("docx_protected.docx");
51 protected_document.save_to_file(&protected_path)?;
52 println!("Wrote {}", protected_path.display());
53
54 Ok(())
55}Sourcepub fn with_custom_property(
self,
name: impl Into<String>,
value: CustomPropertyValue,
) -> Document
pub fn with_custom_property( self, name: impl Into<String>, value: CustomPropertyValue, ) -> Document
Appends a custom property (name/value pair) and returns the document for chaining. See
custom_properties’s doc comment for why order matters here.
Examples found in repository?
16fn main() -> office_toolkit::Result<()> {
17 let properties = DocumentProperties::new()
18 .with_title("Quarterly Report")
19 .with_subject("Q3 results")
20 .with_creator("Jane Doe")
21 .with_keywords("finance, quarterly, report")
22 .with_description("An example document showing document properties.")
23 .with_category("Finance")
24 .with_content_status("Draft");
25 let extended_properties = ExtendedProperties::new()
26 .with_company("Acme Corp.")
27 .with_manager("Jane Manager");
28
29 let metadata_document = Document::new()
30 .with_properties(properties)
31 .with_extended_properties(extended_properties)
32 .with_custom_property("ProjectCode", CustomPropertyValue::Text("Q3-2026".to_string()))
33 .with_custom_property("Budget", CustomPropertyValue::Number(125_000.0))
34 .with_custom_property("Approved", CustomPropertyValue::Bool(false))
35 .with_custom_property("RevisionCount", CustomPropertyValue::Int(3))
36 .with_track_changes(true)
37 .with_paragraph(Paragraph::with_text(
38 "This document carries standard properties (title/author/subject/...), four custom properties, \
39 and has track changes turned on — check File > Info in Word to see them.",
40 ));
41 let metadata_path = output_path("docx_metadata.docx");
42 metadata_document.save_to_file(&metadata_path)?;
43 println!("Wrote {}", metadata_path.display());
44
45 let protected_document = Document::new()
46 .with_protection(ProtectionKind::ReadOnly)
47 .with_paragraph(Paragraph::with_text(
48 "This document is protected as read-only — Word will ask for a password before allowing edits.",
49 ));
50 let protected_path = output_path("docx_protected.docx");
51 protected_document.save_to_file(&protected_path)?;
52 println!("Wrote {}", protected_path.display());
53
54 Ok(())
55}Source§impl Document
impl Document
Sourcepub fn write_to<W>(&self, writer: W) -> Result<W, Error>
pub fn write_to<W>(&self, writer: W) -> Result<W, Error>
Writes this document out as a valid .docx package.
Writes [Content_Types].xml, _rels/.rels, word/document.xml,
word/_rels/document.xml.rels, word/settings.xml, docProps/core.xml,
docProps/app.xml, and — if set/non-empty — word/header1.xml/word/footer1.xml (default)
plus header2.xml/footer2.xml (first page) and header3.xml/ footer3.xml (even pages),
word/styles.xml, word/numbering.xml, word/footnotes.xml, word/endnotes.xml,
word/comments.xml, word/theme/theme1.xml, docProps/custom.xml. webSettings.xml/
fontTable.xml are not written yet; they are optional, not required for the file to open
cleanly. Page setup (size/orientation/margins/ columns) comes from Document.page_setup, a
single document-wide section — see that field’s doc comment for why mid-document section
breaks aren’t modeled.
Trait Implementations§
Source§impl SaveToFile for Document
Available on crate feature word only.
impl SaveToFile for Document
word only.