Skip to main content

deepdoc_core/extract/ooxml/
pptx.rs

1//! PowerPoint (`.pptx`) extractor.
2//!
3//! A deck is a sequence of slides, so the output is a sequence of sections: the
4//! slide's title placeholder becomes the heading (or `Slide N` when it has
5//! none), body placeholders with several paragraphs become lists — that is what
6//! a bulleted text frame actually is — and tables come through as tables.
7//! Speaker notes live in a separate part and are left out.
8
9use std::collections::HashMap;
10use std::path::Path;
11
12use crate::detect::{Format, Sniff};
13use crate::error::{Error, Result};
14use crate::extract::container::Container;
15use crate::extract::ooxml::relationships;
16use crate::extract::xml::{self, Element};
17use crate::extract::{ExtractOpts, Extractor};
18use crate::model::{Block, Document, Inline, Row, Span};
19
20pub struct PptxExtractor;
21
22impl Extractor for PptxExtractor {
23    fn name(&self) -> &'static str {
24        "pptx"
25    }
26
27    fn supports(&self, _path: &Path, sniff: &Sniff) -> bool {
28        crate::detect::detect(sniff) == Some(Format::Pptx)
29    }
30
31    fn extract(&self, path: &Path, _opts: &ExtractOpts) -> Result<Document> {
32        let mut container = Container::open(path)?;
33
34        let slide_names: Vec<String> = container
35            .names_under("ppt/slides/slide")
36            .into_iter()
37            .filter(|name| name.ends_with(".xml"))
38            .collect();
39
40        let mut blocks = Vec::new();
41        for (index, name) in slide_names.iter().enumerate() {
42            let source = container
43                .read(name)
44                .map_err(|message| Error::parse(path, message))?;
45            let rels = rels_name(name).and_then(|name| container.read_optional(&name));
46            let links = relationships(rels.as_deref());
47
48            blocks.extend(
49                parse_slide(&source, index + 1, &links).map_err(|m| Error::parse(path, m))?,
50            );
51        }
52
53        let mut meta = super::core_properties(&mut container);
54        meta.source_format = Some(Format::Pptx);
55        meta.source_path = Some(path.display().to_string());
56        meta.page_count = Some(slide_names.len() as u32);
57
58        Ok(Document { meta, blocks })
59    }
60}
61
62/// `ppt/slides/slide1.xml` → `ppt/slides/_rels/slide1.xml.rels`.
63fn rels_name(slide: &str) -> Option<String> {
64    let (directory, file) = slide.rsplit_once('/')?;
65    Some(format!("{directory}/_rels/{file}.rels"))
66}
67
68/// Parse one slide into blocks. Pure.
69pub fn parse_slide(
70    source: &str,
71    number: usize,
72    links: &HashMap<String, String>,
73) -> std::result::Result<Vec<Block>, String> {
74    let root = xml::parse(source)?;
75
76    let mut heading: Option<Inline> = None;
77    let mut body = Vec::new();
78
79    // Slides after the first start a new page in the output.
80    let mut blocks = if number > 1 {
81        vec![Block::PageBreak {
82            page: number as u32,
83        }]
84    } else {
85        Vec::new()
86    };
87
88    for shape in root.find_all("sp") {
89        let Some(frame) = shape.find("txBody") else {
90            continue;
91        };
92        let paragraphs = text_paragraphs(frame, links);
93        if paragraphs.is_empty() {
94            continue;
95        }
96
97        if heading.is_none() && is_title(shape) {
98            heading = paragraphs.first().map(|(_, inline)| inline.clone());
99            body.extend(paragraphs.into_iter().skip(1));
100        } else {
101            body.extend(paragraphs);
102        }
103    }
104
105    blocks.push(Block::Heading {
106        level: 2,
107        text: heading.unwrap_or_else(|| Inline::text(format!("Slide {number}"))),
108    });
109
110    // One paragraph is a line of text; several are the deck's bullet list.
111    if body.len() > 1 {
112        blocks.push(nest(&body));
113    } else {
114        blocks.extend(body.into_iter().map(|(_, text)| Block::Paragraph { text }));
115    }
116
117    for table in root.find_all("tbl") {
118        if let Some(table) = table_block(table, links) {
119            blocks.push(table);
120        }
121    }
122
123    Ok(blocks)
124}
125
126/// Whether a shape is the slide's title placeholder.
127fn is_title(shape: &Element) -> bool {
128    shape
129        .find("ph")
130        .and_then(|placeholder| placeholder.attr("type"))
131        .is_some_and(|kind| matches!(kind, "title" | "ctrTitle"))
132}
133
134/// The paragraphs of a text frame, with their indent level.
135fn text_paragraphs(frame: &Element, links: &HashMap<String, String>) -> Vec<(u8, Inline)> {
136    frame
137        .find_all("p")
138        .into_iter()
139        .filter_map(|paragraph| {
140            let level = paragraph
141                .child("pPr")
142                .and_then(|properties| properties.attr_number("lvl"))
143                .unwrap_or(0)
144                .clamp(0, 8) as u8;
145            let inline = paragraph_inline(paragraph, links);
146            (!inline.plain_text().trim().is_empty()).then_some((level, inline))
147        })
148        .collect()
149}
150
151fn paragraph_inline(paragraph: &Element, links: &HashMap<String, String>) -> Inline {
152    let mut spans = Vec::new();
153
154    for child in paragraph.elements() {
155        match child.name.as_str() {
156            "r" => {
157                let properties = child.child("rPr");
158                let bold = toggle_attr(properties, "b");
159                let italic = toggle_attr(properties, "i");
160                let text = child.child("t").map(Element::text).unwrap_or_default();
161                if text.is_empty() {
162                    continue;
163                }
164
165                let inner = vec![Span::Text(text)];
166                let styled = match (bold, italic) {
167                    (false, false) => inner,
168                    (true, false) => vec![Span::Bold(inner)],
169                    (false, true) => vec![Span::Italic(inner)],
170                    (true, true) => vec![Span::Bold(vec![Span::Italic(inner)])],
171                };
172
173                // `hlinkClick` names a relationship in the slide's rels part.
174                match properties
175                    .and_then(|p| p.child("hlinkClick"))
176                    .and_then(|link| link.attr("id"))
177                    .and_then(|id| links.get(id))
178                {
179                    Some(href) => spans.push(Span::Link {
180                        href: href.clone(),
181                        text: styled,
182                    }),
183                    None => spans.extend(styled),
184                }
185            }
186            "br" => spans.push(Span::LineBreak),
187            "fld" => {
188                let text = child.child("t").map(Element::text).unwrap_or_default();
189                if !text.is_empty() {
190                    spans.push(Span::Text(text));
191                }
192            }
193            _ => {}
194        }
195    }
196
197    Inline::new(spans)
198}
199
200/// DrawingML writes booleans as attributes (`b="1"`), not child elements.
201fn toggle_attr(properties: Option<&Element>, name: &str) -> bool {
202    match properties.and_then(|p| p.attr(name)) {
203        Some(value) => !matches!(value, "0" | "false"),
204        None => false,
205    }
206}
207
208/// Build nested lists from paragraphs carrying their indent level.
209fn nest(items: &[(u8, Inline)]) -> Block {
210    let mut list_items: Vec<Vec<Block>> = Vec::new();
211
212    let mut index = 0;
213    while index < items.len() {
214        let (level, inline) = &items[index];
215        let mut blocks = vec![Block::Paragraph {
216            text: inline.clone(),
217        }];
218
219        let children_start = index + 1;
220        let mut children_end = children_start;
221        while children_end < items.len() && items[children_end].0 > *level {
222            children_end += 1;
223        }
224        if children_end > children_start {
225            blocks.push(nest(&items[children_start..children_end]));
226        }
227
228        list_items.push(blocks);
229        index = children_end;
230    }
231
232    Block::List {
233        ordered: false,
234        items: list_items,
235    }
236}
237
238fn table_block(table: &Element, links: &HashMap<String, String>) -> Option<Block> {
239    let mut rows: Vec<Row> = Vec::new();
240
241    for row in table.find_all("tr") {
242        let cells: Vec<Inline> = row
243            .find_all("tc")
244            .into_iter()
245            .map(|cell| {
246                let text = text_paragraphs(cell, links)
247                    .into_iter()
248                    .map(|(_, inline)| inline.plain_text())
249                    .collect::<Vec<_>>()
250                    .join(" ");
251                Inline::text(text.trim())
252            })
253            .collect();
254        if !cells.is_empty() {
255            rows.push(Row::new(cells));
256        }
257    }
258
259    if rows.is_empty() {
260        return None;
261    }
262    let header = rows.remove(0);
263    Some(Block::Table {
264        header: Some(header),
265        rows,
266    })
267}
268
269#[cfg(test)]
270mod tests {
271    use super::*;
272
273    fn slide(shapes: &str) -> String {
274        format!(
275            r#"<p:sld xmlns:p="p" xmlns:a="a"><p:cSld><p:spTree>{shapes}</p:spTree></p:cSld></p:sld>"#
276        )
277    }
278
279    fn title_shape(text: &str) -> String {
280        format!(
281            r#"<p:sp><p:nvSpPr><p:nvPr><p:ph type="title"/></p:nvPr></p:nvSpPr>
282               <p:txBody><a:p><a:r><a:t>{text}</a:t></a:r></a:p></p:txBody></p:sp>"#
283        )
284    }
285
286    #[test]
287    fn the_title_placeholder_becomes_the_heading() {
288        let blocks = parse_slide(&slide(&title_shape("Agenda")), 1, &HashMap::new()).unwrap();
289        assert_eq!(
290            blocks,
291            vec![Block::Heading {
292                level: 2,
293                text: Inline::text("Agenda")
294            }]
295        );
296    }
297
298    #[test]
299    fn a_slide_without_a_title_is_numbered() {
300        let blocks = parse_slide(&slide(""), 3, &HashMap::new()).unwrap();
301        assert_eq!(
302            blocks,
303            vec![
304                Block::PageBreak { page: 3 },
305                Block::Heading {
306                    level: 2,
307                    text: Inline::text("Slide 3")
308                },
309            ]
310        );
311    }
312
313    #[test]
314    fn body_paragraphs_become_a_nested_list() {
315        let body = r#"<p:sp><p:txBody>
316              <a:p><a:r><a:t>first</a:t></a:r></a:p>
317              <a:p><a:pPr lvl="1"/><a:r><a:t>deeper</a:t></a:r></a:p>
318              <a:p><a:r><a:t>second</a:t></a:r></a:p>
319            </p:txBody></p:sp>"#;
320        let blocks = parse_slide(
321            &slide(&format!("{}{body}", title_shape("T"))),
322            1,
323            &HashMap::new(),
324        )
325        .unwrap();
326
327        assert_eq!(
328            blocks[1],
329            Block::List {
330                ordered: false,
331                items: vec![
332                    vec![
333                        Block::paragraph("first"),
334                        Block::List {
335                            ordered: false,
336                            items: vec![vec![Block::paragraph("deeper")]],
337                        },
338                    ],
339                    vec![Block::paragraph("second")],
340                ],
341            }
342        );
343    }
344
345    #[test]
346    fn a_single_body_paragraph_stays_a_paragraph() {
347        let body =
348            r#"<p:sp><p:txBody><a:p><a:r><a:t>just text</a:t></a:r></a:p></p:txBody></p:sp>"#;
349        let blocks = parse_slide(
350            &slide(&format!("{}{body}", title_shape("T"))),
351            1,
352            &HashMap::new(),
353        )
354        .unwrap();
355        assert_eq!(blocks[1], Block::paragraph("just text"));
356    }
357
358    #[test]
359    fn runs_carry_drawingml_styling() {
360        let body = r#"<p:sp><p:txBody><a:p>
361              <a:r><a:rPr b="1"/><a:t>bold</a:t></a:r>
362              <a:r><a:rPr i="1"/><a:t> italic</a:t></a:r>
363            </a:p></p:txBody></p:sp>"#;
364        let blocks = parse_slide(&slide(body), 1, &HashMap::new()).unwrap();
365
366        let Block::Paragraph { text } = &blocks[1] else {
367            panic!("expected a paragraph, got {blocks:?}");
368        };
369        assert_eq!(
370            text.spans,
371            vec![
372                Span::Bold(vec![Span::Text("bold".into())]),
373                Span::Italic(vec![Span::Text(" italic".into())]),
374            ]
375        );
376    }
377
378    #[test]
379    fn tables_come_through() {
380        let table = r#"<p:graphicFrame><a:graphic><a:graphicData><a:tbl>
381              <a:tr><a:tc><a:txBody><a:p><a:r><a:t>a</a:t></a:r></a:p></a:txBody></a:tc>
382                    <a:tc><a:txBody><a:p><a:r><a:t>b</a:t></a:r></a:p></a:txBody></a:tc></a:tr>
383              <a:tr><a:tc><a:txBody><a:p><a:r><a:t>1</a:t></a:r></a:p></a:txBody></a:tc>
384                    <a:tc><a:txBody><a:p><a:r><a:t>2</a:t></a:r></a:p></a:txBody></a:tc></a:tr>
385            </a:tbl></a:graphicData></a:graphic></p:graphicFrame>"#;
386        let blocks = parse_slide(
387            &slide(&format!("{}{table}", title_shape("T"))),
388            1,
389            &HashMap::new(),
390        )
391        .unwrap();
392
393        assert_eq!(
394            blocks.last(),
395            Some(&Block::Table {
396                header: Some(Row::from_texts(["a", "b"])),
397                rows: vec![Row::from_texts(["1", "2"])],
398            })
399        );
400    }
401}