Skip to main content

SlideParser

Struct SlideParser 

Source
pub struct SlideParser;
Expand description

Slide parser

Implementations§

Source§

impl SlideParser

Source

pub fn parse(xml: &str) -> Result<ParsedSlide, PptxError>

Parse slide XML content

Examples found in repository?
examples/read_presentation.rs (line 135)
13fn main() -> Result<(), Box<dyn std::error::Error>> {
14    println!("╔════════════════════════════════════════════════════════════╗");
15    println!("║         PPTX Reading & Parsing Demo                        ║");
16    println!("╚════════════════════════════════════════════════════════════╝\n");
17
18    // =========================================================================
19    // Step 1: Create a sample PPTX to read
20    // =========================================================================
21    println!("📝 Step 1: Creating sample presentation...");
22    
23    let slides = vec![
24        SlideContent::new("Welcome to PPTX-RS")
25            .layout(SlideLayout::CenteredTitle)
26            .title_bold(true)
27            .title_color("1F497D"),
28        
29        SlideContent::new("Features Overview")
30            .add_bullet("Create presentations programmatically")
31            .add_bullet("Read existing PPTX files")
32            .add_bullet("Extract text and metadata")
33            .add_bullet("Parse shapes and tables"),
34        
35        SlideContent::new("Technical Details")
36            .layout(SlideLayout::TwoColumn)
37            .add_bullet("XML parsing with xml-rs")
38            .add_bullet("ZIP handling with zip crate")
39            .add_bullet("ECMA-376 compliant")
40            .add_bullet("Rust 2024 edition")
41            .add_bullet("Cross-platform")
42            .add_bullet("No external dependencies"),
43        
44        SlideContent::new("Summary")
45            .add_bullet("Full read/write support")
46            .add_bullet("Comprehensive API")
47            .add_bullet("Well tested"),
48    ];
49    
50    let pptx_data = create_pptx_with_content("PPTX-RS Demo", slides)?;
51    fs::write("sample_presentation.pptx", &pptx_data)?;
52    println!("   ✓ Created sample_presentation.pptx ({} bytes)\n", pptx_data.len());
53
54    // =========================================================================
55    // Step 2: Open and read the presentation
56    // =========================================================================
57    println!("📖 Step 2: Opening presentation...");
58    
59    let reader = PresentationReader::open("sample_presentation.pptx")?;
60    let info = reader.info();
61    
62    println!("   Presentation Info:");
63    println!("   ├── Title: {}", info.title.as_deref().unwrap_or("(none)"));
64    println!("   ├── Creator: {}", info.creator.as_deref().unwrap_or("(none)"));
65    println!("   ├── Slides: {}", info.slide_count);
66    println!("   └── Revision: {}\n", info.revision.unwrap_or(0));
67
68    // =========================================================================
69    // Step 3: Parse each slide
70    // =========================================================================
71    println!("📑 Step 3: Parsing slides...");
72    
73    for i in 0..reader.slide_count() {
74        let slide = reader.get_slide(i)?;
75        
76        println!("\n   Slide {}:", i + 1);
77        println!("   ├── Title: {}", slide.title.as_deref().unwrap_or("(none)"));
78        println!("   ├── Shapes: {}", slide.shapes.len());
79        println!("   ├── Tables: {}", slide.tables.len());
80        
81        if !slide.body_text.is_empty() {
82            println!("   └── Body text:");
83            for (j, text) in slide.body_text.iter().enumerate() {
84                let prefix = if j == slide.body_text.len() - 1 { "       └──" } else { "       ├──" };
85                println!("{}  {}", prefix, text);
86            }
87        } else {
88            println!("   └── Body text: (none)");
89        }
90    }
91
92    // =========================================================================
93    // Step 4: Extract all text
94    // =========================================================================
95    println!("\n📋 Step 4: Extracting all text...");
96    
97    let all_text = reader.extract_all_text()?;
98    println!("   Found {} text items:", all_text.len());
99    for (i, text) in all_text.iter().take(10).enumerate() {
100        println!("   {}. {}", i + 1, text);
101    }
102    if all_text.len() > 10 {
103        println!("   ... and {} more", all_text.len() - 10);
104    }
105
106    // =========================================================================
107    // Step 5: Direct XML parsing (advanced)
108    // =========================================================================
109    println!("\n🔧 Step 5: Direct XML parsing (advanced)...");
110    
111    // You can also parse slide XML directly
112    let sample_xml = r#"<?xml version="1.0" encoding="UTF-8"?>
113    <p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" 
114           xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">
115        <p:cSld>
116            <p:spTree>
117                <p:sp>
118                    <p:nvSpPr>
119                        <p:cNvPr id="2" name="Title"/>
120                        <p:nvPr><p:ph type="title"/></p:nvPr>
121                    </p:nvSpPr>
122                    <p:txBody>
123                        <a:p>
124                            <a:r>
125                                <a:rPr b="1" sz="4400"/>
126                                <a:t>Direct Parse Example</a:t>
127                            </a:r>
128                        </a:p>
129                    </p:txBody>
130                </p:sp>
131            </p:spTree>
132        </p:cSld>
133    </p:sld>"#;
134    
135    let parsed = SlideParser::parse(sample_xml)?;
136    println!("   Parsed XML directly:");
137    println!("   ├── Title: {}", parsed.title.as_deref().unwrap_or("(none)"));
138    println!("   └── Shapes: {}", parsed.shapes.len());
139    
140    if let Some(shape) = parsed.shapes.first() {
141        if let Some(para) = shape.paragraphs.first() {
142            if let Some(run) = para.runs.first() {
143                println!("\n   Text formatting detected:");
144                println!("   ├── Bold: {}", run.bold);
145                println!("   ├── Font size: {:?}", run.font_size);
146                println!("   └── Text: {}", run.text);
147            }
148        }
149    }
150
151    // Cleanup
152    fs::remove_file("sample_presentation.pptx").ok();
153
154    // =========================================================================
155    // Summary
156    // =========================================================================
157    println!("\n╔════════════════════════════════════════════════════════════╗");
158    println!("║                    Demo Complete                           ║");
159    println!("╠════════════════════════════════════════════════════════════╣");
160    println!("║  Capabilities Demonstrated:                                ║");
161    println!("║  ✓ PresentationReader::open() - Open PPTX files            ║");
162    println!("║  ✓ reader.info() - Get presentation metadata               ║");
163    println!("║  ✓ reader.get_slide(i) - Parse individual slides           ║");
164    println!("║  ✓ reader.extract_all_text() - Extract all text            ║");
165    println!("║  ✓ SlideParser::parse() - Direct XML parsing               ║");
166    println!("╚════════════════════════════════════════════════════════════╝");
167
168    Ok(())
169}

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more