docx_lite/
types.rs

1
2#[derive(Debug, Clone, Default)]
3pub struct Document {
4    pub paragraphs: Vec<Paragraph>,
5    pub tables: Vec<Table>,
6}
7
8#[derive(Debug, Clone, Default)]
9pub struct Paragraph {
10    pub runs: Vec<Run>,
11    pub style: Option<String>,
12}
13
14#[derive(Debug, Clone, Default)]
15pub struct Run {
16    pub text: String,
17    pub bold: bool,
18    pub italic: bool,
19    pub underline: bool,
20}
21
22#[derive(Debug, Clone, Default)]
23pub struct Table {
24    pub rows: Vec<TableRow>,
25}
26
27#[derive(Debug, Clone, Default)]
28pub struct TableRow {
29    pub cells: Vec<TableCell>,
30}
31
32#[derive(Debug, Clone, Default)]
33pub struct TableCell {
34    pub paragraphs: Vec<Paragraph>,
35}
36
37impl Document {
38    pub fn new() -> Self {
39        Self::default()
40    }
41
42    pub fn extract_text(&self) -> String {
43        let mut text = String::new();
44
45        // Extract text from paragraphs
46        for paragraph in &self.paragraphs {
47            let para_text = paragraph.to_text();
48            if !para_text.is_empty() {
49                text.push_str(&para_text);
50                text.push('\n');
51            }
52        }
53
54        // Extract text from tables
55        for table in &self.tables {
56            for row in &table.rows {
57                for cell in &row.cells {
58                    for paragraph in &cell.paragraphs {
59                        let para_text = paragraph.to_text();
60                        if !para_text.is_empty() {
61                            text.push_str(&para_text);
62                            text.push('\t'); // Separate cells with tabs
63                        }
64                    }
65                }
66                text.push('\n'); // New line after each row
67            }
68            text.push('\n'); // Extra line after table
69        }
70
71        text
72    }
73}
74
75impl Paragraph {
76    pub fn new() -> Self {
77        Self::default()
78    }
79
80    pub fn to_text(&self) -> String {
81        self.runs.iter()
82            .map(|run| run.text.as_str())
83            .collect::<Vec<_>>()
84            .join("")
85    }
86
87    pub fn add_run(&mut self, run: Run) {
88        self.runs.push(run);
89    }
90}
91
92impl Run {
93    pub fn new(text: String) -> Self {
94        Self {
95            text,
96            ..Default::default()
97        }
98    }
99}
100
101impl Table {
102    pub fn new() -> Self {
103        Self::default()
104    }
105}