Skip to main content

docspec_docx_reader/
lib.rs

1#![forbid(unsafe_code)]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3//! DOCX to `DocSpec` event stream reader.
4//!
5//! This crate provides a [`DocxReader`] that implements [`EventSource`] to convert
6//! DOCX documents into the `DocSpec` event stream format. It uses `quick-xml` for
7//! streaming XML parsing and `zip` for archive extraction.
8//!
9//! # Scope
10//!
11//! **In scope**: Paragraphs (`<w:p>`), direct text (`<w:t>` inside `<w:r>`),
12//! line breaks (`<w:br>` — including `w:type="page"` and `w:type="column"`, all
13//! emitted as `LineBreak`), tabs (`<w:tab>`, emitted as a `Text` event whose
14//! content is the single character `"\t"`), tables (`<w:tbl>`, `<w:tr>`,
15//! `<w:tc>`), lists (`<w:p>` with `<w:numPr>` — ordered and unordered),
16//! hyperlinks (`<w:hyperlink>` — resolved via `word/_rels/document.xml.rels`
17//! and emitted as `StartLink`/`EndLink` events around inline content),
18//! structured document tags (`<w:sdt>` — content emitted normally;
19//! `<w:sdtPr>`/`<w:sdtEndPr>` dropped), tracked insertions and moves
20//! (`<w:ins>`, `<w:moveTo>` — accept-changes semantics), and `DrawingML` images
21//! (`<w:drawing>` — emitted as `Image` events; see the crate README for
22//! `ImageSource` variants and `AssetHandle` usage).
23//! Emits: `StartDocument`, `StartParagraph`, `StartTextStyle`, `Text`,
24//! `EndTextStyle`, `LineBreak`, `EndParagraph`, `StartTable`, `StartTableRow`,
25//! `StartTableCell`, `StartTableHeader`, `EndTableHeader`, `EndTableCell`,
26//! `EndTableRow`, `EndTable`, `StartLink`, `EndLink`, `StartOrderedListItem`,
27//! `EndOrderedListItem`, `StartUnorderedListItem`, `EndUnorderedListItem`,
28//! `Image`, `EndDocument`.
29//!
30//! The elements listed under "Out of scope" are the reader's denylist — their
31//! entire subtree is silently dropped. Every other element (known or unknown)
32//! is parsed normally; the reader continues into its children.
33//!
34//! **Out of scope (subtree silently dropped)**:
35//! - Run styling not listed in the crate README
36//! - Headings (any `<w:pStyle>` value — every paragraph is `StartParagraph`)
37//! - Vertical cell merging (`<w:vMerge>`) — every cell emits with
38//!   `rowspan: None`
39//! - Header rows in nested tables — only the outermost table honors
40//!   `<w:tblHeader>`
41//! - Table-level property exceptions (`<w:tblPrEx>`) — silently ignored
42//! - Table, row, and cell visual properties (`<w:tblPr>`, `<w:trPr>` visual
43//!   fields, `<w:tcPr>` visual fields, `<w:tblGrid>`)
44//! - VML images (`<w:pict>`) — deferred to follow-up; subtree silently dropped
45//! - Comments, footnotes, headers, footers
46//! - Document metadata
47//! - Tracked deletions (`<w:del>`, `<w:moveFrom>`) — accept-changes semantics
48//! - Structured document tag properties (`<w:sdtPr>`, `<w:sdtEndPr>`)
49//! - Field-code hyperlinks (`<w:fldChar>` + `<w:instrText>HYPERLINK ...`):
50//!   legacy form not currently supported; only the modern `<w:hyperlink>`
51//!   element is recognized.
52//!
53//! # Lists
54//!
55//! See the crate README for V1 list semantics and limitations.
56//!
57//! # Streaming Guarantee
58//!
59//! `DocxReader` streams `document.xml` event by event using constant memory
60//! regardless of document size. `_rels/.rels` and
61//! `word/_rels/document.xml.rels` are both fully read into memory at
62//! package-open time (typical combined size < 10 KB even for large documents).
63//! `word/document.xml` is consumed in streaming fashion via `quick-xml`. The
64//! internal event queue remains bounded regardless of document size or
65//! hyperlink count.
66//!
67//! # Quick Start
68//!
69//! ```no_run
70//! use docspec_docx_reader::{DocxReader, EventSource};
71//!
72//! let mut reader = DocxReader::from_path("document.docx")?;
73//! while let Some(event) = reader.next_event()? {
74//!     println!("{event:?}");
75//! }
76//! # Ok::<(), docspec_core::Error>(())
77//! ```
78
79extern crate alloc;
80
81mod asset_provider;
82mod content_types;
83mod document;
84mod numbering;
85mod package;
86mod properties;
87mod rels;
88mod styles;
89mod symbol_fonts;
90
91use std::io::{BufReader, Read, Seek};
92use std::path::Path;
93
94pub use docspec_core::EventSource;
95
96use docspec_core::{Error, Result};
97
98const _: for<'a> fn(&'a content_types::ContentTypes, &str) -> Option<&'a str> =
99    content_types::ContentTypes::lookup;
100fn _image_rel_fields(r: &rels::ImageRel) -> (&str, bool) {
101    (&r.target, r.is_external)
102}
103const _: for<'a> fn(&'a rels::ImageRel) -> (&'a str, bool) = _image_rel_fields;
104
105/// A streaming DOCX reader that implements [`EventSource`].
106///
107/// `DocxReader` parses a DOCX archive and emits `DocSpec` events one at a time.
108/// `<w:p>` paragraphs, `<w:t>` text, `<w:br>` line breaks, `<w:tab>` tabs,
109/// table elements (`<w:tbl>`, `<w:tr>`, `<w:tc>`), and `DrawingML` images
110/// (`<w:drawing>`) are recognized; all other elements are silently ignored.
111///
112/// # Streaming
113///
114/// The reader streams `document.xml` event by event using constant memory.
115/// `_rels/.rels` and `word/_rels/document.xml.rels` are both fully read into
116/// memory at package-open time (typical combined size < 10 KB). The internal
117/// event queue remains bounded regardless of document size or hyperlink count.
118///
119/// # Errors
120///
121/// Returns [`Error::Io`] for I/O failures and [`Error::Parse`] for malformed
122/// archives or XML.
123#[derive(Debug)]
124pub struct DocxReader {
125    inner: document::DocumentReader,
126}
127
128impl DocxReader {
129    /// Creates a `DocxReader` from a file path.
130    ///
131    /// # Errors
132    ///
133    /// Returns [`Error::Io`] if the file cannot be opened. See [`from_reader`](Self::from_reader)
134    /// for additional error conditions.
135    #[inline]
136    pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self> {
137        let file = std::fs::File::open(path.as_ref()).map_err(Error::from)?;
138        Self::from_reader(file)
139    }
140
141    /// Creates a `DocxReader` from any `Read + Seek` source.
142    ///
143    /// The reader must be positioned at the start of a valid DOCX (ZIP) archive.
144    ///
145    /// # Errors
146    ///
147    /// Returns [`Error::Parse`] if the input is not a valid ZIP archive, if
148    /// `_rels/.rels` is missing or malformed, or if the document target entry
149    /// cannot be opened. Returns [`Error::Io`] for I/O failures.
150    #[inline]
151    pub fn from_reader<R: Read + Seek + Send + 'static>(reader: R) -> Result<Self> {
152        let (style_list, numbering, hyperlink_map, image_map, content_types, archive, stream) =
153            package::open_package(reader)?;
154        let xml = quick_xml::Reader::from_reader(BufReader::new(stream));
155        let data = document::DocxData {
156            style_list,
157            hyperlink_map,
158            numbering,
159            image_map,
160        };
161        Ok(Self {
162            inner: document::DocumentReader::from_xml_reader_and_archive(
163                xml,
164                data,
165                archive,
166                content_types,
167            ),
168        })
169    }
170}
171
172impl EventSource for DocxReader {
173    #[inline]
174    fn next_event(&mut self) -> Result<Option<docspec_core::Event>> {
175        self.inner.next_event()
176    }
177}
178
179#[cfg(test)]
180#[cfg(not(coverage))]
181mod tests {
182    #![allow(clippy::unwrap_used, clippy::panic)]
183    use super::*;
184
185    #[test]
186    fn docx_reader_is_send_static() {
187        fn assert_send_static<T: Send + 'static>() {}
188        assert_send_static::<DocxReader>();
189    }
190
191    #[test]
192    fn docx_without_styles_emits_only_paragraphs() {
193        use std::io::{Cursor, Write as _};
194        use zip::ZipWriter;
195
196        let root_rels = r#"<?xml version="1.0" encoding="UTF-8"?>
197<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
198  <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
199</Relationships>"#;
200        let document_xml = r#"<?xml version="1.0" encoding="UTF-8"?>
201<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
202  <w:body>
203    <w:p><w:r><w:t>hi</w:t></w:r></w:p>
204  </w:body>
205</w:document>"#;
206
207        let buf = Cursor::new(Vec::new());
208        let mut writer = ZipWriter::new(buf);
209        let options = zip::write::SimpleFileOptions::default()
210            .compression_method(zip::CompressionMethod::Stored);
211        writer.start_file("_rels/.rels", options).unwrap();
212        writer.write_all(root_rels.as_bytes()).unwrap();
213        writer.start_file("word/document.xml", options).unwrap();
214        writer.write_all(document_xml.as_bytes()).unwrap();
215        let zip_bytes = writer.finish().unwrap().into_inner();
216
217        let mut reader = DocxReader::from_reader(Cursor::new(zip_bytes)).unwrap();
218        let mut events = Vec::new();
219        loop {
220            match reader.next_event() {
221                Ok(Some(event)) => events.push(event),
222                Ok(None) => break,
223                Err(err) => panic!("unexpected error: {err:?}"),
224            }
225        }
226
227        assert_eq!(
228            events,
229            vec![
230                docspec_core::Event::StartDocument {
231                    id: None,
232                    language: None,
233                    metadata: None,
234                },
235                docspec_core::Event::StartParagraph {
236                    alignment: None,
237                    id: None,
238                },
239                docspec_core::Event::Text {
240                    content: "hi".to_string(),
241                },
242                docspec_core::Event::EndParagraph,
243                docspec_core::Event::EndDocument,
244            ]
245        );
246    }
247}