ebook-rs 0.16.4

Pure Rust multi-format eBook engine (EPUB 2/3, MOBI, AZW3, KFX, FB2, LIT, CBZ, PDF, ODT, DOCX, RTF, TXT, MD) featuring Mozilla UniFFI, Readium CFI/LCP, SpeechSynthesis TTS sync, CJK vertical/RTL reflow, EPUB3 optimizer, AI RAG BM25 chunking, zero-copy search, Zstd caching, Python/WASM bindings, and native MCP server.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
use crate::archive::EpubArchive;
use crate::book::Book;
use crate::deobfuscate::FontDeobfuscator;
use crate::error::EbookError;
use crate::layout::RenditionLayout;
use crate::metadata::{Metadata, PageProgressionDirection, SpineItem};
use crate::nav::NavPoint;
use crate::opf::OpfPackage;
use crate::section::Section;
use ahash::AHashMap;
use roxmltree::Document;
use std::io::Read;

/// Microsoft Word (.docx) Office Open XML document parser engine.
pub struct DocxBook;

impl DocxBook {
    /// Parse Microsoft Word (.docx) archive bytes into a unified `Book` instance.
    pub fn parse(bytes: &[u8], title_fallback: &str) -> Result<Book, EbookError> {
        let reader = std::io::Cursor::new(bytes);
        let mut archive = zip::ZipArchive::new(reader)
            .map_err(|e| EbookError::Zip(format!("Failed to open DOCX ZIP archive: {}", e)))?;

        const MAX_DOCX_ENTRIES: usize = 10_000;
        if archive.len() > MAX_DOCX_ENTRIES {
            return Err(EbookError::InvalidFormat(
                "DOCX archive exceeds maximum entry limit".to_string(),
            ));
        }

        // 1. Read word/document.xml
        let mut document_xml = String::new();
        const MAX_DOCX_XML_SIZE: u64 = 64 * 1024 * 1024; // 64 MB limit for document.xml
        const MAX_DOCX_MEDIA_SIZE: u64 = 64 * 1024 * 1024; // 64 MB limit per media file
        const MAX_DOCX_META_SIZE: u64 = 16 * 1024 * 1024; // 16 MB limit for metadata XML
        if let Ok(mut file) = archive.by_name("word/document.xml") {
            file.by_ref()
                .take(MAX_DOCX_XML_SIZE)
                .read_to_string(&mut document_xml)
                .map_err(|e| {
                    EbookError::Io(format!("Failed to read word/document.xml in DOCX: {}", e))
                })?;
        } else {
            return Err(EbookError::InvalidFormat(
                "DOCX archive missing word/document.xml".to_string(),
            ));
        }

        let mut epub_archive = EpubArchive::empty();

        // 2. Extract embedded images from word/media/*
        for i in 0..archive.len() {
            if let Ok(mut file) = archive.by_index(i) {
                let name = file.name().to_string();
                if name.starts_with("word/media/") && !name.ends_with('/') {
                    let mut img_data = Vec::new();
                    if file
                        .by_ref()
                        .take(MAX_DOCX_MEDIA_SIZE)
                        .read_to_end(&mut img_data)
                        .is_ok()
                    {
                        let relative_name = name.strip_prefix("word/").unwrap_or(&name);
                        epub_archive.insert(relative_name, img_data);
                    }
                }
            }
        }

        // 3. Extract metadata from docProps/core.xml
        let mut title = title_fallback.to_string();
        let mut creators = Vec::new();
        let mut description = None;

        if let Ok(mut file) = archive.by_name("docProps/core.xml") {
            let mut core_xml = String::new();
            if file
                .by_ref()
                .take(MAX_DOCX_META_SIZE)
                .read_to_string(&mut core_xml)
                .is_ok()
            {
                if let Ok(doc) = Document::parse(&core_xml) {
                    for node in doc.descendants() {
                        if node.is_element() {
                            let tag = node.tag_name().name();
                            if tag == "title" {
                                if let Some(t) = node.text() {
                                    if !t.trim().is_empty() {
                                        title = t.trim().to_string();
                                    }
                                }
                            } else if tag == "creator" {
                                if let Some(c) = node.text() {
                                    if !c.trim().is_empty() {
                                        creators.push(c.trim().to_string());
                                    }
                                }
                            } else if tag == "description" {
                                if let Some(d) = node.text() {
                                    if !d.trim().is_empty() {
                                        description = Some(d.trim().to_string());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        // 4. Parse relationship map (word/_rels/document.xml.rels)
        let mut rels_map: AHashMap<String, String> = AHashMap::new();
        if let Ok(mut file) = archive.by_name("word/_rels/document.xml.rels") {
            let mut rels_xml = String::new();
            if file
                .by_ref()
                .take(MAX_DOCX_META_SIZE)
                .read_to_string(&mut rels_xml)
                .is_ok()
            {
                if let Ok(doc) = Document::parse(&rels_xml) {
                    for node in doc.descendants() {
                        if node.is_element() && node.tag_name().name() == "Relationship" {
                            if let (Some(id), Some(target)) =
                                (node.attribute("Id"), node.attribute("Target"))
                            {
                                rels_map.insert(id.to_string(), target.to_string());
                            }
                        }
                    }
                }
            }
        }

        // 5. Parse document.xml DOM
        let doc = Document::parse(&document_xml)
            .map_err(|e| EbookError::Xml(format!("Failed to parse DOCX document.xml: {}", e)))?;

        let mut sections = Vec::new();
        let mut spine = Vec::new();
        let mut toc = Vec::new();

        let mut current_html = String::new();
        let mut current_text = String::new();
        let mut section_index = 0;
        let mut current_heading = String::new();

        for node in doc.descendants() {
            if !node.is_element() {
                continue;
            }

            let tag = node.tag_name().name();

            if tag == "p" {
                // Check if paragraph is a Heading or contains page break
                let mut heading_level: Option<u32> = None;
                let mut has_page_break = false;

                for child in node.children() {
                    if child.is_element() {
                        if child.tag_name().name() == "pPr" {
                            for ppr_child in child.children() {
                                if ppr_child.is_element() && ppr_child.tag_name().name() == "pStyle"
                                {
                                    if let Some(val) = ppr_child
                                        .attribute((
                                            "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
                                            "val",
                                        ))
                                        .or_else(|| ppr_child.attribute("val"))
                                    {
                                        let val_low = val.to_lowercase();
                                        if val_low == "heading1" || val_low == "heading 1" || val_low == "1" {
                                            heading_level = Some(1);
                                        } else if val_low == "heading2" || val_low == "heading 2" || val_low == "2" {
                                            heading_level = Some(2);
                                        } else if val_low == "heading3" || val_low == "heading 3" || val_low == "3" {
                                            heading_level = Some(3);
                                        }
                                    }
                                }
                            }
                        } else if child.tag_name().name() == "r" {
                            for r_child in child.children() {
                                if r_child.is_element() && r_child.tag_name().name() == "br" {
                                    if let Some(typ) = r_child.attribute((
                                        "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
                                        "type",
                                    )).or_else(|| r_child.attribute("type")) {
                                        if typ == "page" {
                                            has_page_break = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                let p_text = extract_node_text(&node);
                let p_html = render_paragraph_html(&node, &rels_map);

                if (heading_level == Some(1) || has_page_break) && !current_text.is_empty() {
                    // Flush existing section
                    let sec_href = format!("section_{}.html", section_index);
                    let full_html =
                        format!("<div class=\"docx-section\">\n{}\n</div>", current_html);
                    let char_count = current_text.chars().count();
                    let plain_text_lower = current_text.to_lowercase();

                    sections.push(Section {
                        index: section_index,
                        idref: format!("sec_{}", section_index),
                        href: sec_href.clone(),
                        full_path: sec_href.clone(),
                        raw_html: full_html.clone(),
                        processed_html: full_html,
                        plain_text: current_text.clone(),
                        plain_text_lower,
                        char_count,
                        viewport_width: None,
                        viewport_height: None,
                    });

                    spine.push(SpineItem {
                        idref: format!("sec_{}", section_index),
                        linear: true,
                        properties: Vec::new(),
                        index: section_index,
                        href: sec_href.clone(),
                        media_type: "application/xhtml+xml".to_string(),
                    });

                    let label = if !current_heading.is_empty() {
                        current_heading.clone()
                    } else {
                        format!("Section {}", section_index + 1)
                    };

                    toc.push(NavPoint {
                        id: format!("nav_{}", toc.len() + 1),
                        label,
                        href: sec_href,
                        full_path: format!("section_{}.html", section_index),
                        subitems: Vec::new(),
                    });

                    section_index += 1;
                    current_html.clear();
                    current_text.clear();
                    current_heading.clear();
                }

                if let Some(level) = heading_level {
                    if level == 1 && current_heading.is_empty() {
                        current_heading = p_text.clone();
                    }
                    current_html.push_str(&format!(
                        "<h{}>{}</h{}>\n",
                        level,
                        xml_escape(&p_text),
                        level
                    ));
                } else if !p_html.is_empty() {
                    current_html.push_str(&format!("<p>{}</p>\n", p_html));
                }

                if !p_text.is_empty() {
                    current_text.push_str(&p_text);
                    current_text.push('\n');
                }
            } else if tag == "tbl" {
                let tbl_html = render_table_html(&node);
                current_html.push_str(&tbl_html);
            }
        }

        // Flush trailing section
        if !current_text.is_empty() || sections.is_empty() {
            let sec_href = format!("section_{}.html", section_index);
            let full_html = format!("<div class=\"docx-section\">\n{}\n</div>", current_html);
            let char_count = current_text.chars().count();
            let plain_text_lower = current_text.to_lowercase();

            sections.push(Section {
                index: section_index,
                idref: format!("sec_{}", section_index),
                href: sec_href.clone(),
                full_path: sec_href.clone(),
                raw_html: full_html.clone(),
                processed_html: full_html,
                plain_text: current_text.clone(),
                plain_text_lower,
                char_count,
                viewport_width: None,
                viewport_height: None,
            });

            spine.push(SpineItem {
                idref: format!("sec_{}", section_index),
                linear: true,
                properties: Vec::new(),
                index: section_index,
                href: sec_href.clone(),
                media_type: "application/xhtml+xml".to_string(),
            });

            let label = if !current_heading.is_empty() {
                current_heading
            } else {
                format!("Section {}", section_index + 1)
            };

            toc.push(NavPoint {
                id: format!("nav_{}", toc.len() + 1),
                label,
                href: sec_href.clone(),
                full_path: sec_href,
                subitems: Vec::new(),
            });
        }

        let metadata = Metadata {
            title,
            creators,
            publishers: Vec::new(),
            languages: vec!["en".to_string()],
            rights: None,
            description,
            identifier: None,
            pub_date: None,
            modified_date: None,
            subjects: vec!["Document".to_string()],
            cover_id: None,
            cover_href: None,
            direction: PageProgressionDirection::Ltr,
            meta_properties: AHashMap::new(),
            accessibility: Default::default(),
        };

        let opf = OpfPackage {
            version: "3.0".to_string(),
            opf_path: "content.opf".to_string(),
            opf_dir: "".to_string(),
            metadata,
            manifest: AHashMap::new(),
            spine,
            guide: Vec::new(),
            toc_item_id: None,
            nav_item_id: None,
        };

        let mut book = Book {
            archive: epub_archive,
            opf,
            layout: RenditionLayout::default(),
            toc,
            landmarks: Vec::new(),
            page_list: Vec::new(),
            sections,
            locations: crate::locations::Locations::default(),
            annotations: crate::annotations::AnnotationManager::default(),
            before_display_hooks: Vec::new(),
            font_deobfuscator: FontDeobfuscator::parse_encryption_xml(""),
            media_overlays: AHashMap::new(),
            render_cache: parking_lot::Mutex::new(AHashMap::new()),
        };

        book.generate_locations(1000);
        Ok(book)
    }
}

fn extract_node_text(node: &roxmltree::Node) -> String {
    let mut buf = String::new();
    for desc in node.descendants() {
        if desc.is_element() && desc.tag_name().name() == "t" {
            if let Some(t) = desc.text() {
                buf.push_str(t);
            }
        }
    }
    buf
}

fn render_paragraph_html(node: &roxmltree::Node, rels: &AHashMap<String, String>) -> String {
    let mut html = String::new();

    for child in node.children() {
        if !child.is_element() {
            continue;
        }

        let tag = child.tag_name().name();

        if tag == "r" {
            let mut is_bold = false;
            let mut is_italic = false;
            let mut is_underline = false;
            let mut is_strike = false;
            let mut text = String::new();
            let mut img_src: Option<String> = None;

            for r_child in child.children() {
                if !r_child.is_element() {
                    continue;
                }
                let r_tag = r_child.tag_name().name();

                if r_tag == "rPr" {
                    for pr in r_child.children() {
                        if !pr.is_element() {
                            continue;
                        }
                        match pr.tag_name().name() {
                            "b" => is_bold = true,
                            "i" => is_italic = true,
                            "u" => is_underline = true,
                            "strike" => is_strike = true,
                            _ => {}
                        }
                    }
                } else if r_tag == "t" {
                    if let Some(t) = r_child.text() {
                        text.push_str(t);
                    }
                } else if r_tag == "drawing" {
                    for desc in r_child.descendants() {
                        if desc.is_element() && desc.tag_name().name() == "blip" {
                            if let Some(embed_id) = desc
                                .attribute((
                                    "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
                                    "embed",
                                ))
                                .or_else(|| desc.attribute("r:embed"))
                            {
                                if let Some(target) = rels.get(embed_id) {
                                    img_src = Some(target.clone());
                                }
                            }
                        }
                    }
                }
            }

            if let Some(src) = img_src {
                html.push_str(&format!(
                    "<img src=\"{}\" alt=\"image\" />",
                    xml_escape(&src)
                ));
            }

            if !text.is_empty() {
                let mut escaped = xml_escape(&text);
                if is_strike {
                    escaped = format!("<s>{}</s>", escaped);
                }
                if is_underline {
                    escaped = format!("<u>{}</u>", escaped);
                }
                if is_italic {
                    escaped = format!("<em>{}</em>", escaped);
                }
                if is_bold {
                    escaped = format!("<strong>{}</strong>", escaped);
                }
                html.push_str(&escaped);
            }
        }
    }

    html
}

fn render_table_html(node: &roxmltree::Node) -> String {
    let mut out = String::from("<table>\n");

    for row in node.children() {
        if row.is_element() && row.tag_name().name() == "tr" {
            out.push_str("  <tr>\n");
            for cell in row.children() {
                if cell.is_element() && cell.tag_name().name() == "tc" {
                    let cell_text = extract_node_text(&cell);
                    out.push_str(&format!("    <td>{}</td>\n", xml_escape(&cell_text)));
                }
            }
            out.push_str("  </tr>\n");
        }
    }

    out.push_str("</table>\n");
    out
}

fn xml_escape(input: &str) -> String {
    input
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&apos;")
}