Skip to main content

Paragraph

Struct Paragraph 

Source
pub struct Paragraph {
Show 15 fields pub runs: Vec<Run>, pub alignment: Option<Alignment>, pub style_id: Option<String>, pub numbering_id: Option<u32>, pub numbering_level: u8, pub line_spacing: Option<u32>, pub space_before: Option<u32>, pub space_after: Option<u32>, pub shading_color: Option<String>, pub border: bool, pub keep_with_next: bool, pub keep_lines_together: bool, pub page_break_before: bool, pub tabs: Vec<TabStop>, pub contextual_spacing: bool,
}
Expand description

A paragraph: a sequence of runs, plus paragraph-level formatting.

Fields§

§runs: Vec<Run>

The runs that make up this paragraph, in order.

§alignment: Option<Alignment>

The paragraph’s horizontal alignment, or None to leave it unspecified (inherits from the paragraph style / Word’s default). Overrides the alignment of style_id’s style, if any.

§style_id: Option<String>

The id of a paragraph-type Style to apply (w:pStyle), or None to use the document’s default paragraph style. The referenced style must actually be declared in Document.styles for the document to be well-formed — this is not validated when writing.

§numbering_id: Option<u32>

The id of a NumberingDefinition to apply (w:numPr/w:numId), making this paragraph an item of that list, or None for a regular paragraph. The referenced definition must actually be declared in Document.numbering_definitions for the document to be well-formed — not validated when writing, same convention as style_id.

§numbering_level: u8

Which indent level of numbering_id’s list this paragraph is at (w:numPr/w:ilvl, 0-indexed). Only meaningful when numbering_id is Some; must be within the range of levels the referenced NumberingDefinition actually declares — not validated when writing.

§line_spacing: Option<u32>

This paragraph’s line spacing (w:spacing/@line, written together with w:spacing/@lineRule="auto"), or None to leave it unspecified. Unlike space_before/space_after (raw twips), this is in w:spacing’s “auto” units — 240ths of a single line, so 240 is single spacing, 360 is 1.5 lines, 480 is double — matching what Word’s own line-spacing dropdown offers. The twips-based atLeast/exact line-height modes (w:lineRule’s other two values, meant for exact point-based line heights rather than a multiple of the current font) aren’t modeled.

§space_before: Option<u32>

Extra space before this paragraph, in twips (w:spacing/@before, ST_TwipsMeasure, twentieths of a point) — raw units, no conversion, matching Run.character_spacing’s precedent. None leaves it unspecified. w:spacing/@beforeAutospacing (letting Word compute it automatically instead) isn’t modeled.

§space_after: Option<u32>

Extra space after this paragraph, in twips, mirroring space_before.

§shading_color: Option<String>

This paragraph’s background shading color (w:shd/@fill), mirroring Run.shading_color — see that field’s doc comment for the same val/color fixed-pair convention.

§border: bool

Whether this paragraph has a border around it (w:pBdr), mirroring Run.text_border — a simple on/off switch with the same fixed appearance (val="single" sz="4" space="0" color="auto"), applied to all four sides (top/left/bottom/right). CT_PBdr’s between (a rule drawn between paragraphs sharing this same border, when several consecutive paragraphs all have it) and bar (a vertical bar in the margin, used for revision-style paragraph marking) aren’t modeled, same scope-reduction posture as text_border not exposing all of CT_Border’s richness.

§keep_with_next: bool

Whether this paragraph should stay on the same page as the one following it (w:keepNext, CT_OnOff) — Word moves both to the next page together rather than letting a page break fall between them. Commonly set on heading paragraphs, so a heading never ends up alone at the bottom of a page with its content starting on the next one.

§keep_lines_together: bool

Whether every line of this paragraph must stay together on the same page (w:keepLines, CT_OnOff) — prevents the paragraph itself from being split across a page break partway through.

§page_break_before: bool

Whether this paragraph always starts on a new page (w:pageBreakBefore, CT_OnOff) — a page break is forced immediately before it, regardless of how much room is left on the current page. Distinct from RunContent::Break(BreakKind::Page), which inserts an explicit page break wherever it appears within a run’s content, mid-paragraph; this is a paragraph-level property instead.

§tabs: Vec<TabStop>

This paragraph’s custom tab stops (w:tabs, CT_Tabs), in order. Left empty (the default) to fall back entirely to Word’s own default tab stops (evenly spaced, typically every 720 twips/half inch) — setting even one custom stop here does not disable Word’s defaults beyond it, per ECMA-376.

§contextual_spacing: bool

Whether to ignore the spacing above/below this paragraph when the paragraph immediately before/after it shares the same paragraph style (w:contextualSpacing, CT_OnOff) — commonly set on list item styles, so consecutive list items don’t get extra vertical gaps between them even if the style itself sets space_before/ space_after.

Implementations§

Source§

impl Paragraph

Source

pub fn new() -> Paragraph

Creates an empty paragraph.

Examples found in repository?
examples/docx_page_layout.rs (line 62)
61fn heading(text: &str, new_page: bool) -> Paragraph {
62    Paragraph::new()
63        .with_run(Run::new(text).with_bold(true).with_font_size(28))
64        .with_page_break_before(new_page)
65}
More examples
Hide additional examples
examples/docx_tables.rs (line 93)
92fn heading(text: &str, new_page: bool) -> Paragraph {
93    Paragraph::new()
94        .with_run(Run::new(text).with_bold(true).with_font_size(28))
95        .with_page_break_before(new_page)
96}
examples/docx_images_and_charts.rs (line 30)
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}
38
39/// A minimal bar chart with literal (not cell-referenced) data — enough to
40/// demonstrate embedding, without needing a companion spreadsheet.
41fn sample_chart_space() -> ChartSpace {
42    let categories = StringData::new()
43        .with_point(StringPoint::new(0, "Q1"))
44        .with_point(StringPoint::new(1, "Q2"))
45        .with_point(StringPoint::new(2, "Q3"));
46    let values = NumericData::new()
47        .with_point(NumericPoint::new(0, "1200"))
48        .with_point(NumericPoint::new(1, "1350"))
49        .with_point(NumericPoint::new(2, "980"));
50
51    let series = BarSeries::new(0, 0)
52        .with_categories(AxisDataSource::String(StringDataSource::literal(
53            categories,
54        )))
55        .with_values(NumericDataSource::literal(values));
56
57    let bar_chart = BarChart::new(BarDirection::Column, 1, 2).with_series(series);
58    let category_axis = CategoryAxis::new(1, AxisPosition::Bottom, 2);
59    let value_axis = ValueAxis::new(2, AxisPosition::Left, 1);
60
61    let plot_area = PlotArea::new()
62        .with_chart(ChartType::Bar(bar_chart))
63        .with_axis(Axis::Category(category_axis))
64        .with_axis(Axis::Value(value_axis));
65
66    ChartSpace::new(Chart::new(plot_area))
67}
68
69fn heading(text: &str, new_page: bool) -> Paragraph {
70    Paragraph::new()
71        .with_run(Run::new(text).with_bold(true).with_font_size(28))
72        .with_page_break_before(new_page)
73}
examples/docx_styles_and_lists.rs (line 45)
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}
72
73fn heading(text: &str, new_page: bool) -> Paragraph {
74    Paragraph::new()
75        .with_run(Run::new(text).with_bold(true).with_font_size(28))
76        .with_page_break_before(new_page)
77}
examples/docx_navigation_and_annotations.rs (line 25)
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}
85
86fn heading(text: &str, new_page: bool) -> Paragraph {
87    Paragraph::new()
88        .with_run(Run::new(text).with_bold(true).with_font_size(28))
89        .with_page_break_before(new_page)
90}
examples/docx_text_formatting.rs (line 21)
16fn main() -> office_toolkit::Result<()> {
17    let path = output_path("docx_text_formatting.docx");
18
19    let document = Document::new()
20        .with_paragraph(heading("Docx text formatting — bold, italic, underline, strike", false))
21        .with_paragraph(Paragraph::new().with_run(Run::new("Bold text.").with_bold(true)))
22        .with_paragraph(Paragraph::new().with_run(Run::new("Italic text.").with_italic(true)))
23        .with_paragraph(Paragraph::new().with_run(Run::new("Single underline.").with_underline(UnderlineStyle::Single)))
24        .with_paragraph(Paragraph::new().with_run(Run::new("Wavy underline.").with_underline(UnderlineStyle::Wave)))
25        .with_paragraph(Paragraph::new().with_run(Run::new("Strikethrough text.").with_strike(true)))
26        .with_paragraph(heading("Colors and highlight", true))
27        .with_paragraph(Paragraph::new().with_run(Run::new("Red text on the default background.").with_color("FF0000")))
28        .with_paragraph(Paragraph::new().with_run(Run::new("Text highlighted in yellow.").with_highlight(Highlight::Yellow)))
29        .with_paragraph(
30            Paragraph::new()
31                .with_run(Run::new("Larger, custom font.").with_font_size(32).with_font_family("Georgia")),
32        )
33        .with_paragraph(heading("Superscript and subscript", true))
34        .with_paragraph(
35            Paragraph::new()
36                .with_run(Run::new("Water is H"))
37                .with_run(Run::new("2").with_vertical_align(VerticalAlign::Subscript))
38                .with_run(Run::new("O.")),
39        )
40        .with_paragraph(
41            Paragraph::new()
42                .with_run(Run::new("Squared: x"))
43                .with_run(Run::new("2").with_vertical_align(VerticalAlign::Superscript))
44                .with_run(Run::new(".")),
45        )
46        .with_paragraph(heading("Small caps, all caps, character spacing", true))
47        .with_paragraph(Paragraph::new().with_run(Run::new("rendered in small caps").with_small_caps(true)))
48        .with_paragraph(Paragraph::new().with_run(Run::new("rendered in all caps").with_all_caps(true)))
49        .with_paragraph(Paragraph::new().with_run(Run::new("Widely spaced letters.").with_character_spacing(120)))
50        .with_paragraph(heading("Paragraph alignment", true))
51        .with_paragraph(Paragraph::with_text("Left-aligned (the default).").with_alignment(Alignment::Left))
52        .with_paragraph(Paragraph::with_text("Centered.").with_alignment(Alignment::Center))
53        .with_paragraph(Paragraph::with_text("Right-aligned.").with_alignment(Alignment::Right))
54        .with_paragraph(
55            Paragraph::with_text(
56                "Justified: this line is long enough for Word to stretch the spacing between words so both edges line up.",
57            )
58            .with_alignment(Alignment::Justify),
59        )
60        .with_paragraph(heading("Tab stops", true))
61        .with_paragraph(
62            Paragraph::new()
63                .with_tab(TabStop::new(1_440).with_alignment(TabStopAlignment::Center))
64                .with_tab(TabStop::new(2_880).with_alignment(TabStopAlignment::Right).with_leader(TabLeader::Dot))
65                .with_run(Run::new("Left\tCentered\tRight, dot leader")),
66        );
67
68    document.save_to_file(&path)?;
69    println!("Wrote {}", path.display());
70    Ok(())
71}
72
73/// A bold section heading, optionally starting a new page — used to give
74/// each feature group its own page in the rendered document.
75fn heading(text: &str, new_page: bool) -> Paragraph {
76    Paragraph::new()
77        .with_run(Run::new(text).with_bold(true).with_font_size(28))
78        .with_page_break_before(new_page)
79}
Source

pub fn with_text(text: impl Into<String>) -> Paragraph

Creates a paragraph containing a single run with the given text.

Examples found in repository?
examples/hello_world_docx.rs (line 16)
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
Hide additional examples
examples/docx_theme.rs (line 17)
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}
examples/docx_metadata_and_protection.rs (lines 37-40)
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}
examples/docx_page_layout.rs (line 27)
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}
examples/docx_styles_and_lists.rs (line 41)
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}
examples/docx_navigation_and_annotations.rs (line 58)
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}
Source

pub fn with_run(self, run: Run) -> Paragraph

Appends a run and returns the paragraph for chaining.

Examples found in repository?
examples/docx_page_layout.rs (line 63)
61fn heading(text: &str, new_page: bool) -> Paragraph {
62    Paragraph::new()
63        .with_run(Run::new(text).with_bold(true).with_font_size(28))
64        .with_page_break_before(new_page)
65}
More examples
Hide additional examples
examples/docx_tables.rs (line 94)
92fn heading(text: &str, new_page: bool) -> Paragraph {
93    Paragraph::new()
94        .with_run(Run::new(text).with_bold(true).with_font_size(28))
95        .with_page_break_before(new_page)
96}
examples/docx_images_and_charts.rs (line 30)
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}
38
39/// A minimal bar chart with literal (not cell-referenced) data — enough to
40/// demonstrate embedding, without needing a companion spreadsheet.
41fn sample_chart_space() -> ChartSpace {
42    let categories = StringData::new()
43        .with_point(StringPoint::new(0, "Q1"))
44        .with_point(StringPoint::new(1, "Q2"))
45        .with_point(StringPoint::new(2, "Q3"));
46    let values = NumericData::new()
47        .with_point(NumericPoint::new(0, "1200"))
48        .with_point(NumericPoint::new(1, "1350"))
49        .with_point(NumericPoint::new(2, "980"));
50
51    let series = BarSeries::new(0, 0)
52        .with_categories(AxisDataSource::String(StringDataSource::literal(
53            categories,
54        )))
55        .with_values(NumericDataSource::literal(values));
56
57    let bar_chart = BarChart::new(BarDirection::Column, 1, 2).with_series(series);
58    let category_axis = CategoryAxis::new(1, AxisPosition::Bottom, 2);
59    let value_axis = ValueAxis::new(2, AxisPosition::Left, 1);
60
61    let plot_area = PlotArea::new()
62        .with_chart(ChartType::Bar(bar_chart))
63        .with_axis(Axis::Category(category_axis))
64        .with_axis(Axis::Value(value_axis));
65
66    ChartSpace::new(Chart::new(plot_area))
67}
68
69fn heading(text: &str, new_page: bool) -> Paragraph {
70    Paragraph::new()
71        .with_run(Run::new(text).with_bold(true).with_font_size(28))
72        .with_page_break_before(new_page)
73}
examples/docx_styles_and_lists.rs (line 46)
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}
72
73fn heading(text: &str, new_page: bool) -> Paragraph {
74    Paragraph::new()
75        .with_run(Run::new(text).with_bold(true).with_font_size(28))
76        .with_page_break_before(new_page)
77}
examples/docx_navigation_and_annotations.rs (lines 26-28)
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}
85
86fn heading(text: &str, new_page: bool) -> Paragraph {
87    Paragraph::new()
88        .with_run(Run::new(text).with_bold(true).with_font_size(28))
89        .with_page_break_before(new_page)
90}
examples/docx_text_formatting.rs (line 21)
16fn main() -> office_toolkit::Result<()> {
17    let path = output_path("docx_text_formatting.docx");
18
19    let document = Document::new()
20        .with_paragraph(heading("Docx text formatting — bold, italic, underline, strike", false))
21        .with_paragraph(Paragraph::new().with_run(Run::new("Bold text.").with_bold(true)))
22        .with_paragraph(Paragraph::new().with_run(Run::new("Italic text.").with_italic(true)))
23        .with_paragraph(Paragraph::new().with_run(Run::new("Single underline.").with_underline(UnderlineStyle::Single)))
24        .with_paragraph(Paragraph::new().with_run(Run::new("Wavy underline.").with_underline(UnderlineStyle::Wave)))
25        .with_paragraph(Paragraph::new().with_run(Run::new("Strikethrough text.").with_strike(true)))
26        .with_paragraph(heading("Colors and highlight", true))
27        .with_paragraph(Paragraph::new().with_run(Run::new("Red text on the default background.").with_color("FF0000")))
28        .with_paragraph(Paragraph::new().with_run(Run::new("Text highlighted in yellow.").with_highlight(Highlight::Yellow)))
29        .with_paragraph(
30            Paragraph::new()
31                .with_run(Run::new("Larger, custom font.").with_font_size(32).with_font_family("Georgia")),
32        )
33        .with_paragraph(heading("Superscript and subscript", true))
34        .with_paragraph(
35            Paragraph::new()
36                .with_run(Run::new("Water is H"))
37                .with_run(Run::new("2").with_vertical_align(VerticalAlign::Subscript))
38                .with_run(Run::new("O.")),
39        )
40        .with_paragraph(
41            Paragraph::new()
42                .with_run(Run::new("Squared: x"))
43                .with_run(Run::new("2").with_vertical_align(VerticalAlign::Superscript))
44                .with_run(Run::new(".")),
45        )
46        .with_paragraph(heading("Small caps, all caps, character spacing", true))
47        .with_paragraph(Paragraph::new().with_run(Run::new("rendered in small caps").with_small_caps(true)))
48        .with_paragraph(Paragraph::new().with_run(Run::new("rendered in all caps").with_all_caps(true)))
49        .with_paragraph(Paragraph::new().with_run(Run::new("Widely spaced letters.").with_character_spacing(120)))
50        .with_paragraph(heading("Paragraph alignment", true))
51        .with_paragraph(Paragraph::with_text("Left-aligned (the default).").with_alignment(Alignment::Left))
52        .with_paragraph(Paragraph::with_text("Centered.").with_alignment(Alignment::Center))
53        .with_paragraph(Paragraph::with_text("Right-aligned.").with_alignment(Alignment::Right))
54        .with_paragraph(
55            Paragraph::with_text(
56                "Justified: this line is long enough for Word to stretch the spacing between words so both edges line up.",
57            )
58            .with_alignment(Alignment::Justify),
59        )
60        .with_paragraph(heading("Tab stops", true))
61        .with_paragraph(
62            Paragraph::new()
63                .with_tab(TabStop::new(1_440).with_alignment(TabStopAlignment::Center))
64                .with_tab(TabStop::new(2_880).with_alignment(TabStopAlignment::Right).with_leader(TabLeader::Dot))
65                .with_run(Run::new("Left\tCentered\tRight, dot leader")),
66        );
67
68    document.save_to_file(&path)?;
69    println!("Wrote {}", path.display());
70    Ok(())
71}
72
73/// A bold section heading, optionally starting a new page — used to give
74/// each feature group its own page in the rendered document.
75fn heading(text: &str, new_page: bool) -> Paragraph {
76    Paragraph::new()
77        .with_run(Run::new(text).with_bold(true).with_font_size(28))
78        .with_page_break_before(new_page)
79}
Source

pub fn with_alignment(self, alignment: Alignment) -> Paragraph

Sets the paragraph’s alignment and returns it for chaining.

Examples found in repository?
examples/docx_text_formatting.rs (line 51)
16fn main() -> office_toolkit::Result<()> {
17    let path = output_path("docx_text_formatting.docx");
18
19    let document = Document::new()
20        .with_paragraph(heading("Docx text formatting — bold, italic, underline, strike", false))
21        .with_paragraph(Paragraph::new().with_run(Run::new("Bold text.").with_bold(true)))
22        .with_paragraph(Paragraph::new().with_run(Run::new("Italic text.").with_italic(true)))
23        .with_paragraph(Paragraph::new().with_run(Run::new("Single underline.").with_underline(UnderlineStyle::Single)))
24        .with_paragraph(Paragraph::new().with_run(Run::new("Wavy underline.").with_underline(UnderlineStyle::Wave)))
25        .with_paragraph(Paragraph::new().with_run(Run::new("Strikethrough text.").with_strike(true)))
26        .with_paragraph(heading("Colors and highlight", true))
27        .with_paragraph(Paragraph::new().with_run(Run::new("Red text on the default background.").with_color("FF0000")))
28        .with_paragraph(Paragraph::new().with_run(Run::new("Text highlighted in yellow.").with_highlight(Highlight::Yellow)))
29        .with_paragraph(
30            Paragraph::new()
31                .with_run(Run::new("Larger, custom font.").with_font_size(32).with_font_family("Georgia")),
32        )
33        .with_paragraph(heading("Superscript and subscript", true))
34        .with_paragraph(
35            Paragraph::new()
36                .with_run(Run::new("Water is H"))
37                .with_run(Run::new("2").with_vertical_align(VerticalAlign::Subscript))
38                .with_run(Run::new("O.")),
39        )
40        .with_paragraph(
41            Paragraph::new()
42                .with_run(Run::new("Squared: x"))
43                .with_run(Run::new("2").with_vertical_align(VerticalAlign::Superscript))
44                .with_run(Run::new(".")),
45        )
46        .with_paragraph(heading("Small caps, all caps, character spacing", true))
47        .with_paragraph(Paragraph::new().with_run(Run::new("rendered in small caps").with_small_caps(true)))
48        .with_paragraph(Paragraph::new().with_run(Run::new("rendered in all caps").with_all_caps(true)))
49        .with_paragraph(Paragraph::new().with_run(Run::new("Widely spaced letters.").with_character_spacing(120)))
50        .with_paragraph(heading("Paragraph alignment", true))
51        .with_paragraph(Paragraph::with_text("Left-aligned (the default).").with_alignment(Alignment::Left))
52        .with_paragraph(Paragraph::with_text("Centered.").with_alignment(Alignment::Center))
53        .with_paragraph(Paragraph::with_text("Right-aligned.").with_alignment(Alignment::Right))
54        .with_paragraph(
55            Paragraph::with_text(
56                "Justified: this line is long enough for Word to stretch the spacing between words so both edges line up.",
57            )
58            .with_alignment(Alignment::Justify),
59        )
60        .with_paragraph(heading("Tab stops", true))
61        .with_paragraph(
62            Paragraph::new()
63                .with_tab(TabStop::new(1_440).with_alignment(TabStopAlignment::Center))
64                .with_tab(TabStop::new(2_880).with_alignment(TabStopAlignment::Right).with_leader(TabLeader::Dot))
65                .with_run(Run::new("Left\tCentered\tRight, dot leader")),
66        );
67
68    document.save_to_file(&path)?;
69    println!("Wrote {}", path.display());
70    Ok(())
71}
Source

pub fn with_style_id(self, style_id: impl Into<String>) -> Paragraph

Sets the paragraph style to apply (by id) and returns it for chaining.

Examples found in repository?
examples/docx_styles_and_lists.rs (line 42)
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}
Source

pub fn with_numbering(self, numbering_id: u32, level: u8) -> Paragraph

Makes this paragraph an item of numbering_id’s list, at the given indent level (0-indexed), and returns it for chaining.

Examples found in repository?
examples/docx_styles_and_lists.rs (line 51)
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}
Source

pub fn with_line_spacing(self, line_spacing: u32) -> Paragraph

Sets the paragraph’s line spacing (in w:spacing’s “auto” units — 240 is single, 360 is 1.5 lines, 480 is double) and returns it for chaining.

Source

pub fn with_space_before(self, space_before: u32) -> Paragraph

Sets extra space before this paragraph, in twips, and returns it for chaining.

Source

pub fn with_space_after(self, space_after: u32) -> Paragraph

Sets extra space after this paragraph, in twips, and returns it for chaining.

Source

pub fn with_shading_color(self, shading_color: impl Into<String>) -> Paragraph

Sets the paragraph’s background shading color and returns it for chaining.

Source

pub fn with_border(self, border: bool) -> Paragraph

Sets whether this paragraph has a border around it and returns it for chaining.

Source

pub fn with_keep_with_next(self, keep_with_next: bool) -> Paragraph

Sets whether this paragraph stays on the same page as the one following it and returns it for chaining. See keep_with_next’s doc comment.

Source

pub fn with_keep_lines_together(self, keep_lines_together: bool) -> Paragraph

Sets whether every line of this paragraph must stay together on the same page and returns it for chaining. See keep_lines_together’s doc comment.

Source

pub fn with_page_break_before(self, page_break_before: bool) -> Paragraph

Sets whether this paragraph always starts on a new page and returns it for chaining. See page_break_before’s doc comment.

Examples found in repository?
examples/docx_images_and_charts.rs (line 72)
69fn heading(text: &str, new_page: bool) -> Paragraph {
70    Paragraph::new()
71        .with_run(Run::new(text).with_bold(true).with_font_size(28))
72        .with_page_break_before(new_page)
73}
More examples
Hide additional examples
examples/docx_navigation_and_annotations.rs (line 89)
86fn heading(text: &str, new_page: bool) -> Paragraph {
87    Paragraph::new()
88        .with_run(Run::new(text).with_bold(true).with_font_size(28))
89        .with_page_break_before(new_page)
90}
examples/docx_page_layout.rs (line 64)
61fn heading(text: &str, new_page: bool) -> Paragraph {
62    Paragraph::new()
63        .with_run(Run::new(text).with_bold(true).with_font_size(28))
64        .with_page_break_before(new_page)
65}
examples/docx_styles_and_lists.rs (line 76)
73fn heading(text: &str, new_page: bool) -> Paragraph {
74    Paragraph::new()
75        .with_run(Run::new(text).with_bold(true).with_font_size(28))
76        .with_page_break_before(new_page)
77}
examples/docx_tables.rs (line 95)
92fn heading(text: &str, new_page: bool) -> Paragraph {
93    Paragraph::new()
94        .with_run(Run::new(text).with_bold(true).with_font_size(28))
95        .with_page_break_before(new_page)
96}
examples/docx_text_formatting.rs (line 78)
75fn heading(text: &str, new_page: bool) -> Paragraph {
76    Paragraph::new()
77        .with_run(Run::new(text).with_bold(true).with_font_size(28))
78        .with_page_break_before(new_page)
79}
Source

pub fn with_tab(self, tab: TabStop) -> Paragraph

Appends a custom tab stop and returns the paragraph for chaining.

Examples found in repository?
examples/docx_text_formatting.rs (line 63)
16fn main() -> office_toolkit::Result<()> {
17    let path = output_path("docx_text_formatting.docx");
18
19    let document = Document::new()
20        .with_paragraph(heading("Docx text formatting — bold, italic, underline, strike", false))
21        .with_paragraph(Paragraph::new().with_run(Run::new("Bold text.").with_bold(true)))
22        .with_paragraph(Paragraph::new().with_run(Run::new("Italic text.").with_italic(true)))
23        .with_paragraph(Paragraph::new().with_run(Run::new("Single underline.").with_underline(UnderlineStyle::Single)))
24        .with_paragraph(Paragraph::new().with_run(Run::new("Wavy underline.").with_underline(UnderlineStyle::Wave)))
25        .with_paragraph(Paragraph::new().with_run(Run::new("Strikethrough text.").with_strike(true)))
26        .with_paragraph(heading("Colors and highlight", true))
27        .with_paragraph(Paragraph::new().with_run(Run::new("Red text on the default background.").with_color("FF0000")))
28        .with_paragraph(Paragraph::new().with_run(Run::new("Text highlighted in yellow.").with_highlight(Highlight::Yellow)))
29        .with_paragraph(
30            Paragraph::new()
31                .with_run(Run::new("Larger, custom font.").with_font_size(32).with_font_family("Georgia")),
32        )
33        .with_paragraph(heading("Superscript and subscript", true))
34        .with_paragraph(
35            Paragraph::new()
36                .with_run(Run::new("Water is H"))
37                .with_run(Run::new("2").with_vertical_align(VerticalAlign::Subscript))
38                .with_run(Run::new("O.")),
39        )
40        .with_paragraph(
41            Paragraph::new()
42                .with_run(Run::new("Squared: x"))
43                .with_run(Run::new("2").with_vertical_align(VerticalAlign::Superscript))
44                .with_run(Run::new(".")),
45        )
46        .with_paragraph(heading("Small caps, all caps, character spacing", true))
47        .with_paragraph(Paragraph::new().with_run(Run::new("rendered in small caps").with_small_caps(true)))
48        .with_paragraph(Paragraph::new().with_run(Run::new("rendered in all caps").with_all_caps(true)))
49        .with_paragraph(Paragraph::new().with_run(Run::new("Widely spaced letters.").with_character_spacing(120)))
50        .with_paragraph(heading("Paragraph alignment", true))
51        .with_paragraph(Paragraph::with_text("Left-aligned (the default).").with_alignment(Alignment::Left))
52        .with_paragraph(Paragraph::with_text("Centered.").with_alignment(Alignment::Center))
53        .with_paragraph(Paragraph::with_text("Right-aligned.").with_alignment(Alignment::Right))
54        .with_paragraph(
55            Paragraph::with_text(
56                "Justified: this line is long enough for Word to stretch the spacing between words so both edges line up.",
57            )
58            .with_alignment(Alignment::Justify),
59        )
60        .with_paragraph(heading("Tab stops", true))
61        .with_paragraph(
62            Paragraph::new()
63                .with_tab(TabStop::new(1_440).with_alignment(TabStopAlignment::Center))
64                .with_tab(TabStop::new(2_880).with_alignment(TabStopAlignment::Right).with_leader(TabLeader::Dot))
65                .with_run(Run::new("Left\tCentered\tRight, dot leader")),
66        );
67
68    document.save_to_file(&path)?;
69    println!("Wrote {}", path.display());
70    Ok(())
71}
Source

pub fn with_contextual_spacing(self, contextual_spacing: bool) -> Paragraph

Sets whether to ignore spacing above/below this paragraph when adjacent to a paragraph of the same style, and returns it for chaining. See contextual_spacing’s doc comment.

Source

pub fn text(&self) -> String

The paragraph’s text: the concatenation of its text runs’ text. Image and field runs contribute nothing (not even a placeholder character).

Examples found in repository?
examples/hello_world_docx.rs (line 25)
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}

Trait Implementations§

Source§

impl Clone for Paragraph

Source§

fn clone(&self) -> Paragraph

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Paragraph

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for Paragraph

Source§

fn default() -> Paragraph

Returns the “default value” for a type. Read more
Source§

impl PartialEq for Paragraph

Source§

fn eq(&self, other: &Paragraph) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Paragraph

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.