pptx-to-md 1.0.0

Parse Microsoft PowerPoint files (.pptx) and OpenDocument Presentations (.odp) into Markdown (.md)
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
use super::{Result, Slide};
use crate::PresentationMetadata;
use crate::constants::{
    COMMENTS_NAMESPACE, NOTES_SLIDE_NAMESPACE, SLIDE_LAYOUT_NAMESPACE, SLIDE_MASTER_NAMESPACE,
};
use crate::metadata::{parse_pptx_metadata, render_presentation_markdown};
use crate::parse_rels::{parse_hyperlink_rels, parse_relationships};
use crate::parse_xml::{InheritedPositions, extract_inherited_positions};
use crate::parser_config::ParserConfig;
use rayon::prelude::*;
use std::sync::Arc;
use std::{collections::HashMap, io::Read, path::Path};

/// Holds the internal representation of a loaded PowerPoint (pptx) container.
///
/// `PptxContainer` provides functionalities for accessing slides and their resources
/// directly from a loaded pptx file. It parses and stores XML slides content,
/// relationships (`rels`) files, and associated resources such as images.
pub struct PptxContainer {
    pub config: ParserConfig,
    archive: zip::ZipArchive<std::fs::File>,
    pub slide_paths: Vec<String>,
    pub slide_count: u32,
    metadata: PresentationMetadata,
}

impl PptxContainer {
    /// Opens a PowerPoint pptx file and initializes a `PptxContainer`.
    ///
    /// _For new code that should support both `.pptx` and `.odp`, prefer
    /// [`PresentationContainer`]. This type remains available for PPTX-only
    /// workflows and backwards compatibility._
    ///
    /// Processes the given file, extracting its internal files into memory. After initialization, the
    /// container holds slide XML data, relationship files (*.rels), and associated resources.
    ///
    /// # Arguments
    ///
    /// - `path`: Path to the PPTX file.
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing:
    /// - `Ok(PptxContainer)`: structured container instance upon successful file opening.
    /// - `Err(Error)`: if file access or internal unzip operations fail.
    ///
    /// # Errors
    ///
    /// Errors are returned on file access problems or failures during the unzipping process.
    pub fn open(path: &Path, config: ParserConfig) -> Result<Self> {
        let file = std::fs::File::open(path)?;
        let mut archive = zip::ZipArchive::new(file)?;

        let mut slide_paths: Vec<String> = Vec::new();
        let mut slide_count = 0;

        for i in 0..archive.len() {
            let file = archive.by_index(i)?;
            let name = file.name().to_string();

            if name.starts_with("ppt/slides/slide") && name.ends_with(".xml") {
                slide_paths.push(name);
                slide_count += 1;
            }
        }

        sort_slide_paths(&mut slide_paths);

        let core_xml = read_optional_archive_file(&mut archive, "docProps/core.xml")?;
        let metadata = parse_pptx_metadata(core_xml.as_deref())?;

        Ok(Self {
            archive,
            slide_paths,
            config,
            slide_count,
            metadata,
        })
    }

    /// Parses the data of all slides for each path present in the containers' `slide_path` vector.
    ///
    /// # Note
    /// Parsing is synchronous and in-memory, image data is extracted
    pub fn parse_all(&mut self) -> Result<Vec<Slide>> {
        let mut slides = Vec::new();
        let count = self.slide_paths.len();

        for i in 0..count {
            let path = &self.slide_paths[i].clone();
            if let Some(slide) = self.load_slide(path)? {
                slides.push(slide);
            }
        }

        Ok(slides)
    }

    pub fn metadata(&self) -> &PresentationMetadata {
        &self.metadata
    }

    pub fn convert_to_md(&mut self) -> Result<String> {
        let slides = self.parse_all()?;
        render_presentation_markdown(
            &self.metadata,
            self.config.include_presentation_metadata,
            slides,
        )
    }

    pub fn convert_to_md_multi_threaded(&mut self) -> Result<String> {
        let slides = self.parse_all_multi_threaded()?;
        render_presentation_markdown(
            &self.metadata,
            self.config.include_presentation_metadata,
            slides,
        )
    }

    /// Parses all slides in the presentation with optimized multithreaded processing.
    ///
    /// This method uses Rayon for parallel processing by:
    /// 1. Preloading all necessary data sequentially (I/O-bound operations)
    /// 2. Performing CPU-intensive XML parsing in parallel
    /// 3. Using shared references for thread-safe data access
    ///
    /// # Returns
    ///
    /// * `Result<Vec<Slide>>` - List of all parsed slides
    pub fn parse_all_multi_threaded(&mut self) -> Result<Vec<Slide>> {
        // Clone paths upfront to avoid holding reference to self
        let slide_paths = self.slide_paths.clone();
        let config = self.config.clone();
        let mut raw_data = Vec::with_capacity(slide_paths.len());
        let mut all_image_data = HashMap::new();

        for slide_path in &slide_paths {
            // Read slide XML and relationships
            let slide_xml = self.read_file_from_archive(slide_path)?;
            let rels_path = self.get_slide_rels_path(slide_path);
            let rels_data = self.read_file_from_archive(&rels_path).ok();
            let hyperlinks = rels_data
                .as_deref()
                .map(parse_hyperlink_rels)
                .transpose()?
                .unwrap_or_default();
            let slide_number = Slide::extract_slide_number(slide_path).unwrap_or(0);
            let inherited_positions =
                self.resolve_inherited_positions(slide_path, rels_data.as_deref())?;
            let speaker_notes = self.resolve_speaker_notes(slide_path, rels_data.as_deref())?;
            let comments = self.resolve_comments(slide_path, rels_data.as_deref())?;

            // Preload images if enabled
            let mut slide_images = Vec::new();
            let mut resource_diagnostics = Vec::new();
            if config.extract_images {
                if let Some(ref data) = rels_data {
                    slide_images = crate::parse_rels::parse_slide_rels(data)?;
                }

                for img_ref in &slide_images {
                    let path = PptxContainer::resolve_target_path(slide_path, &img_ref.target);
                    match self.read_file_from_archive(&path) {
                        Ok(data) => {
                            all_image_data.entry(img_ref.target.clone()).or_insert(data);
                        }
                        Err(error) => resource_diagnostics.push(crate::ParseDiagnostic {
                            severity: crate::DiagnosticSeverity::Warning,
                            message: format!("Image resource could not be loaded: {error}"),
                            source: Some(path),
                        }),
                    }
                }
            }

            raw_data.push((
                slide_path.clone(),
                slide_number,
                slide_xml,
                slide_images,
                inherited_positions,
                speaker_notes,
                comments,
                hyperlinks,
                resource_diagnostics,
            ));
        }

        // Share image data atomically across threads
        let shared_image_data = Arc::new(all_image_data);

        // Parallel processing starts here (CPU-bound tasks)
        let slides: Result<Vec<_>> = raw_data
            .into_par_iter()
            .map(
                |(
                    path,
                    number,
                    xml,
                    images,
                    inherited_positions,
                    speaker_notes,
                    comments,
                    hyperlinks,
                    resource_diagnostics,
                )| {
                    // Parse XML in parallel (CPU-intensive)
                    let mut parsed = crate::parse_xml::parse_slide_document_with_hyperlinks(
                        &xml,
                        &inherited_positions,
                        &hyperlinks,
                    )?;
                    parsed.diagnostics.extend(resource_diagnostics);

                    // Resolve image data from shared registry
                    let mut image_map = HashMap::new();
                    if config.extract_images {
                        for img_ref in &images {
                            if let Some(data) = shared_image_data.get(&img_ref.target) {
                                image_map.insert(img_ref.id.clone(), data.clone());
                            }
                        }
                    }

                    // Build slide
                    let mut slide = Slide::new_semantic(
                        path,
                        number,
                        parsed.elements,
                        parsed.blocks,
                        speaker_notes,
                        comments,
                        images,
                        image_map,
                        config.clone(),
                        parsed.diagnostics,
                    );
                    slide.link_images();
                    Ok(slide)
                },
            )
            .collect();

        slides
    }

    pub fn iter_slides(&mut self) -> SlideIterator<'_> {
        SlideIterator::new(self)
    }

    /// Loads a slide from the PPTX file by its index.
    ///
    /// # Arguments
    ///
    /// * `index` - The zero-based index of the slide to load.
    ///
    /// # Returns
    ///
    /// * `Ok(Some(Slide))` - The parsed slide if found and successfully processed.
    /// * `Ok(None)` - If the index is out of bounds.
    /// * `Err(_)` - If there was an error loading or parsing the slide.
    ///
    /// # Example
    ///
    /// ```
    /// // let mut streamer = open(Path::new("presentation.pptx"))?;
    /// // if let Ok(Some(slide)) = streamer.load_slide(0) {
    ///     // println!("Loaded first slide: {}", slide.slide_number);
    /// // }
    /// ```
    pub fn load_slide(&mut self, slide_path: &str) -> Result<Option<Slide>> {
        // load xml data
        let slide_data = self.read_file_from_archive(slide_path)?;

        // load relationship file
        let rels_path = self.get_slide_rels_path(slide_path);
        let rels_data = self.read_file_from_archive(&rels_path).ok();
        let hyperlinks = rels_data
            .as_deref()
            .map(parse_hyperlink_rels)
            .transpose()?
            .unwrap_or_default();

        // parse slide and preload images
        let slide_number = Slide::extract_slide_number(slide_path).unwrap_or(0);
        let inherited_positions =
            self.resolve_inherited_positions(slide_path, rels_data.as_deref())?;
        let speaker_notes = self.resolve_speaker_notes(slide_path, rels_data.as_deref())?;
        let comments = self.resolve_comments(slide_path, rels_data.as_deref())?;
        let mut parsed = crate::parse_xml::parse_slide_document_with_hyperlinks(
            &slide_data,
            &inherited_positions,
            &hyperlinks,
        )?;

        let mut images = Vec::new();
        let mut image_data = HashMap::new();

        if self.config.extract_images {
            // extract images from relationships
            if let Some(ref rels_bytes) = rels_data {
                images = crate::parse_rels::parse_slide_rels(rels_bytes)?;
            }

            for img_ref in &images {
                let img_path = Self::resolve_target_path(slide_path, &img_ref.target);
                match self.read_file_from_archive(&img_path) {
                    Ok(data) => {
                        image_data.insert(img_ref.id.clone(), data);
                    }
                    Err(error) => parsed.diagnostics.push(crate::ParseDiagnostic {
                        severity: crate::DiagnosticSeverity::Warning,
                        message: format!("Image resource could not be loaded: {error}"),
                        source: Some(img_path),
                    }),
                }
            }
        }

        let config = self.config.clone();

        let mut slide = Slide::new_semantic(
            slide_path.to_string(),
            slide_number,
            parsed.elements,
            parsed.blocks,
            speaker_notes,
            comments,
            images,
            image_data,
            config,
            parsed.diagnostics,
        );

        slide.link_images();
        Ok(Some(slide))
    }

    /// Reads a file from the PPTX archive by its internal path.
    ///
    /// # Arguments
    ///
    /// * `path` - The internal path of the file within the PPTX archive.
    ///
    /// # Returns
    ///
    /// * `Ok(Vec<u8>)` - The content of the file as a byte vector.
    /// * `Err(_)` - If the file could not be found or read.
    ///
    /// # Notes
    ///
    /// This is an internal method used to extract individual files from the
    /// PPTX archive (which is essentially a ZIP file).
    pub fn read_file_from_archive(&mut self, path: &str) -> Result<Vec<u8>> {
        let mut file = self.archive.by_name(path)?;
        let mut content = Vec::new();
        file.read_to_end(&mut content)?;
        Ok(content)
    }

    /// Constructs the path to the relationships file for a given slide.
    ///
    /// # Arguments
    ///
    /// * `slide_path` - The internal path of the slide file.
    ///
    /// # Returns
    ///
    /// The path to the corresponding relationships (.rels) file.
    ///
    /// # Example
    ///
    /// ```
    /// // For a slide path "ppt/slides/slide1.xml"
    /// // Returns "ppt/slides/_rels/slide1.xml.rels"
    pub fn get_slide_rels_path(&self, slide_path: &str) -> String {
        let mut rels_path = slide_path.to_string();
        if let Some(pos) = rels_path.rfind('/') {
            rels_path.insert_str(pos + 1, "_rels/");
        }
        rels_path.push_str(".rels");
        rels_path
    }

    fn resolve_inherited_positions(
        &mut self,
        slide_path: &str,
        slide_rels_data: Option<&[u8]>,
    ) -> Result<InheritedPositions> {
        let Some(slide_rels_data) = slide_rels_data else {
            return Ok(InheritedPositions::default());
        };

        let slide_relationships = parse_relationships(slide_rels_data)?;
        let Some(layout_target) = slide_relationships
            .iter()
            .find(|rel| rel.rel_type == SLIDE_LAYOUT_NAMESPACE)
            .map(|rel| rel.target.as_str())
        else {
            return Ok(InheritedPositions::default());
        };

        let layout_path = Self::resolve_target_path(slide_path, layout_target);
        let layout_xml = self.read_file_from_archive(&layout_path)?;
        let layout_rels_path = self.get_slide_rels_path(&layout_path);
        let layout_rels_data = self.read_file_from_archive(&layout_rels_path).ok();

        let master_positions = if let Some(layout_rels_data) = layout_rels_data.as_deref() {
            let layout_relationships = parse_relationships(layout_rels_data)?;
            if let Some(master_target) = layout_relationships
                .iter()
                .find(|rel| rel.rel_type == SLIDE_MASTER_NAMESPACE)
                .map(|rel| rel.target.as_str())
            {
                let master_path = Self::resolve_target_path(&layout_path, master_target);
                let master_xml = self.read_file_from_archive(&master_path)?;
                extract_inherited_positions(&master_xml, &InheritedPositions::default())?
            } else {
                InheritedPositions::default()
            }
        } else {
            InheritedPositions::default()
        };

        extract_inherited_positions(&layout_xml, &master_positions)
    }

    fn resolve_speaker_notes(
        &mut self,
        slide_path: &str,
        slide_rels_data: Option<&[u8]>,
    ) -> Result<Vec<crate::TextElement>> {
        let Some(slide_rels_data) = slide_rels_data else {
            return Ok(Vec::new());
        };
        let relationships = parse_relationships(slide_rels_data)?;
        let Some(notes_target) = relationships
            .iter()
            .find(|rel| rel.rel_type == NOTES_SLIDE_NAMESPACE)
            .map(|rel| rel.target.as_str())
        else {
            return Ok(Vec::new());
        };
        let notes_path = Self::resolve_target_path(slide_path, notes_target);
        let notes_xml = self.read_file_from_archive(&notes_path)?;
        let notes_rels = self
            .read_file_from_archive(&self.get_slide_rels_path(&notes_path))
            .ok();
        let hyperlinks = notes_rels
            .as_deref()
            .map(parse_hyperlink_rels)
            .transpose()?
            .unwrap_or_default();
        crate::parse_xml::parse_speaker_notes_xml_with_hyperlinks(&notes_xml, &hyperlinks)
    }

    fn resolve_comments(
        &mut self,
        slide_path: &str,
        slide_rels_data: Option<&[u8]>,
    ) -> Result<Vec<crate::TextElement>> {
        let Some(slide_rels_data) = slide_rels_data else {
            return Ok(Vec::new());
        };
        let relationships = parse_relationships(slide_rels_data)?;
        let Some(comment_target) = relationships
            .iter()
            .find(|rel| rel.rel_type == COMMENTS_NAMESPACE || rel.rel_type.ends_with("/comments"))
            .map(|rel| rel.target.as_str())
        else {
            return Ok(Vec::new());
        };
        let comment_path = Self::resolve_target_path(slide_path, comment_target);
        let comment_xml = self.read_file_from_archive(&comment_path)?;
        let comment_rels = self
            .read_file_from_archive(&self.get_slide_rels_path(&comment_path))
            .ok();
        let hyperlinks = comment_rels
            .as_deref()
            .map(parse_hyperlink_rels)
            .transpose()?
            .unwrap_or_default();
        crate::parse_xml::parse_comments_xml_with_hyperlinks(&comment_xml, &hyperlinks)
    }

    pub fn resolve_target_path(base_path: &str, target: &str) -> String {
        let mut parts: Vec<&str> = if target.starts_with('/') {
            Vec::new()
        } else {
            let mut parts: Vec<&str> = base_path.split('/').collect();
            let _ = parts.pop();
            parts
        };

        for part in target.split('/') {
            match part {
                "" | "." => {}
                ".." => {
                    let _ = parts.pop();
                }
                _ => parts.push(part),
            }
        }

        parts.join("/")
    }
}

fn read_optional_archive_file(
    archive: &mut zip::ZipArchive<std::fs::File>,
    path: &str,
) -> Result<Option<Vec<u8>>> {
    let mut file = match archive.by_name(path) {
        Ok(file) => file,
        Err(zip::result::ZipError::FileNotFound) => return Ok(None),
        Err(error) => return Err(error.into()),
    };
    let mut content = Vec::new();
    file.read_to_end(&mut content)?;
    Ok(Some(content))
}

fn sort_slide_paths(slide_paths: &mut [String]) {
    slide_paths.sort_by(|left, right| {
        Slide::extract_slide_number(left)
            .cmp(&Slide::extract_slide_number(right))
            .then_with(|| left.cmp(right))
    });
}

/// An iterator for streaming slides from a PPTX file.
///
/// This iterator allows processing slides one by one, which is more
/// memory-efficient than loading all slides at once. It iterates through
/// all slides in the presentation in order.
///
/// # Example
///
/// ```
/// // let mut streamer = PptxStreamer::open(Path::new("presentation.pptx"))?;
/// // for slide_result in streamer.iter_slides() {
/// //    match slide_result {
/// //        Ok(slide) => println!("Processing slide {}", slide.slide_number),
/// //        Err(e) => eprintln!("Error: {:?}", e),
/// //    }
/// // }
/// ```
pub struct SlideIterator<'a> {
    container: &'a mut PptxContainer,
    current_paths: Vec<String>, // Pfade beim Erstellen des Iterators kopieren
    current_index: usize,
}

impl<'a> SlideIterator<'a> {
    /// Creates a new SlideIterator from a PptxStreamer.
    ///
    /// # Arguments
    ///
    /// * `container` - A mutable reference to a PptxStreamer that will be used to load slides.
    ///
    /// # Returns
    ///
    /// A new SlideIterator instance that will iterate through all slides in the presentation.
    fn new(container: &'a mut PptxContainer) -> Self {
        let current_paths = container.slide_paths.clone();
        Self {
            container,
            current_paths,
            current_index: 0,
        }
    }
}

impl<'a> Iterator for SlideIterator<'a> {
    type Item = Result<Slide>;

    /// Advances the iterator and returns the next slide.
    ///
    /// This method loads and processes the next slide from the PPTX file.
    /// It's automatically called when you use the iterator in a for loop.
    ///
    /// # Returns
    ///
    /// * `Some(Ok(Slide))` - The next slide was successfully loaded and processed.
    /// * `Some(Err(_))` - There was an error loading or processing the next slide.
    /// * `None` - There are no more slides to process.
    fn next(&mut self) -> Option<Self::Item> {
        if self.current_index >= self.current_paths.len() {
            return None;
        }

        let slide_path = &self.current_paths[self.current_index];
        self.current_index += 1;

        match self.container.load_slide(slide_path) {
            Ok(Some(slide)) => Some(Ok(slide)),
            Ok(None) => self.next(), // Skip und weiter zum nächsten
            Err(e) => Some(Err(e)),
        }
    }
}

#[cfg(test)]
#[path = "../tests/unit/container.rs"]
mod tests;