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
//! Public API module
//!
//! High-level API for working with PowerPoint presentations.
use crate::exc::{PptxError, Result};
use crate::export::html::export_to_html;
use crate::generator::{create_pptx_with_content, Image, SlideContent};
use crate::import::import_pptx;
use std::path::Path;
use std::process::Command;
/// Represents a PowerPoint presentation
#[derive(Debug, Clone, Default)]
pub struct Presentation {
title: String,
slides: Vec<SlideContent>,
}
impl Presentation {
/// Create a new empty presentation
pub fn new() -> Self {
Presentation {
title: String::new(),
slides: Vec::new(),
}
}
/// Create a presentation with a title
pub fn with_title(title: &str) -> Self {
Presentation {
title: title.to_string(),
slides: Vec::new(),
}
}
/// Set the presentation title
pub fn title(mut self, title: &str) -> Self {
self.title = title.to_string();
self
}
/// Add a slide to the presentation
pub fn add_slide(mut self, slide: SlideContent) -> Self {
self.slides.push(slide);
self
}
/// Append slides from another presentation
pub fn add_presentation(mut self, other: Presentation) -> Self {
self.slides.extend(other.slides);
self
}
/// Get the number of slides
pub fn slide_count(&self) -> usize {
self.slides.len()
}
/// Get the slides in the presentation
pub fn slides(&self) -> &[SlideContent] {
&self.slides
}
/// Get the presentation title
pub fn get_title(&self) -> &str {
&self.title
}
/// Build the presentation as PPTX bytes
pub fn build(&self) -> Result<Vec<u8>> {
if self.slides.is_empty() {
return Err(PptxError::InvalidState("Presentation has no slides".into()));
}
create_pptx_with_content(&self.title, self.slides.clone())
.map_err(|e| PptxError::Generic(e.to_string()))
}
/// Save the presentation to a file
pub fn save<P: AsRef<Path>>(&self, path: P) -> Result<()> {
let data = self.build()?;
std::fs::write(path, data)?;
Ok(())
}
/// Create a presentation from a PPTX file
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self> {
let path_str = path.as_ref().to_string_lossy();
import_pptx(&path_str)
}
/// Export the presentation to HTML
pub fn save_as_html<P: AsRef<Path>>(&self, path: P) -> Result<()> {
let html = export_to_html(self)?;
std::fs::write(path, html)?;
Ok(())
}
/// Export the presentation to PDF using LibreOffice
///
/// Requires LibreOffice to be installed and available via `soffice` command.
/// On macOS, it also checks `/Applications/LibreOffice.app/Contents/MacOS/soffice`.
pub fn save_as_pdf<P: AsRef<Path>>(&self, output_path: P) -> Result<()> {
// Create a temp file
let temp_dir = std::env::temp_dir();
let temp_filename = format!("ppt_rs_{}.pptx", uuid::Uuid::new_v4());
let temp_path = temp_dir.join(&temp_filename);
// Save current presentation to temp file
self.save(&temp_path)?;
// Try to find soffice
let soffice_cmd = if cfg!(target_os = "macos") {
if Path::new("/Applications/LibreOffice.app/Contents/MacOS/soffice").exists() {
"/Applications/LibreOffice.app/Contents/MacOS/soffice"
} else {
"soffice"
}
} else {
"soffice"
};
// Get output directory
let output_parent = output_path.as_ref().parent().unwrap_or(Path::new("."));
// Run conversion
// soffice --headless --convert-to pdf <temp_path> --outdir <output_dir>
let result = Command::new(soffice_cmd)
.arg("--headless")
.arg("--convert-to")
.arg("pdf")
.arg(&temp_path)
.arg("--outdir")
.arg(output_parent)
.output();
// Clean up temp file (ignore error)
let _ = std::fs::remove_file(&temp_path);
match result {
Ok(output) => {
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(PptxError::Generic(format!(
"LibreOffice conversion failed: {}",
stderr
)));
}
}
Err(e) => {
return Err(PptxError::Generic(format!(
"Failed to execute libreoffice: {}",
e
)));
}
}
// LibreOffice creates file with same basename but .pdf extension in outdir
// The generated file will be temp_filename.pdf (since input was temp_filename.pptx)
let generated_pdf_name = temp_filename.replace(".pptx", ".pdf");
let generated_pdf_path = output_parent.join(&generated_pdf_name);
if generated_pdf_path.exists() {
std::fs::rename(&generated_pdf_path, output_path.as_ref())?;
Ok(())
} else {
Err(PptxError::Generic("PDF output file not found".to_string()))
}
}
/// Export slides to PNG images
///
/// Requires LibreOffice (for PDF conversion) and `pdftoppm` (from poppler).
/// Images will be named `slide-1.png`, `slide-2.png`, etc. in the output directory.
pub fn save_as_png<P: AsRef<Path>>(&self, output_dir: P) -> Result<()> {
let output_dir = output_dir.as_ref();
if !output_dir.exists() {
std::fs::create_dir_all(output_dir)?;
}
// Create temp PDF
let temp_dir = std::env::temp_dir();
let temp_pdf_name = format!("ppt_rs_temp_{}.pdf", uuid::Uuid::new_v4());
let temp_pdf_path = temp_dir.join(&temp_pdf_name);
// Convert to PDF first
self.save_as_pdf(&temp_pdf_path)?;
// Convert PDF to PNGs using pdftoppm
// pdftoppm -png <pdf_file> <image_prefix>
let prefix = output_dir.join("slide");
let status = Command::new("pdftoppm")
.arg("-png")
.arg(&temp_pdf_path)
.arg(&prefix)
.status()
.map_err(|e| PptxError::Generic(format!("Failed to execute pdftoppm: {}", e)))?;
// Cleanup temp PDF
let _ = std::fs::remove_file(&temp_pdf_path);
if !status.success() {
return Err(PptxError::Generic("pdftoppm conversion failed".to_string()));
}
Ok(())
}
/// Create a presentation from a PDF file (each page becomes a slide)
///
/// Requires `pdftoppm` (from poppler) to be installed.
pub fn from_pdf<P: AsRef<Path>>(path: P) -> Result<Self> {
let path = path.as_ref();
if !path.exists() {
return Err(PptxError::NotFound(format!(
"PDF file not found: {}",
path.display()
)));
}
// Create temp dir for images
let temp_dir = std::env::temp_dir().join(format!("ppt_rs_import_{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&temp_dir)?;
// Convert PDF to PNGs
let prefix = temp_dir.join("page");
let status = Command::new("pdftoppm")
.arg("-png")
.arg(path)
.arg(&prefix)
.status()
.map_err(|e| PptxError::Generic(format!("Failed to execute pdftoppm: {}", e)))?;
if !status.success() {
let _ = std::fs::remove_dir_all(&temp_dir);
return Err(PptxError::Generic("pdftoppm failed".to_string()));
}
// Read images and create slides
let mut pres = Presentation::new();
// Set title from filename
if let Some(stem) = path.file_stem() {
pres = pres.title(&stem.to_string_lossy());
}
// Read dir
let mut entries: Vec<_> = std::fs::read_dir(&temp_dir)?
.filter_map(|e| e.ok())
.collect();
// Sort by filename to ensure page order
// pdftoppm names files like page-1.png, page-2.png... page-10.png
// Default string sort might put page-10 before page-2
// We need to sort by length then by name, or rely on pdftoppm zero padding (it usually does -01 if needed, but safer to trust number)
// pdftoppm default is -1, -2... -10.
// So page-1.png, page-10.png, page-2.png.
// We need natural sort.
entries.sort_by_key(|e| {
let name = e.file_name().to_string_lossy().to_string();
// Extract number from end
// "page-1.png" -> 1
if let Some(start) = name.rfind('-') {
if let Some(end) = name.rfind('.') {
if start < end {
if let Ok(num) = name[start + 1..end].parse::<u32>() {
return num;
}
}
}
}
0 // Fallback
});
for entry in entries {
let path = entry.path();
if path.extension().map_or(false, |e| e == "png") {
// Create slide with full screen image
let image = Image::from_path(&path).map_err(|e| PptxError::Generic(e))?;
// Add image to slide
// Use a default layout?
// Just create a slide with this image
// We'll center it.
// Assuming standard 16:9 slide (10x5.625 inches) -> 9144000 x 5143500 EMU
// But we don't know image dimensions here easily without reading it.
// Image builder defaults to auto size?
// Let's just add it.
let mut slide = SlideContent::new("");
slide.images.push(image);
pres = pres.add_slide(slide);
}
}
let _ = std::fs::remove_dir_all(&temp_dir);
Ok(pres)
}
/// Export the presentation to Markdown format
///
/// # Arguments
/// * `path` - Output file path
///
/// # Example
/// ```
/// # use ppt_rs::api::Presentation;
/// # use ppt_rs::generator::SlideContent;
/// # let pres = Presentation::with_title("My Presentation")
/// # .add_slide(SlideContent::new("Slide 1").add_bullet("Point 1"));
/// # // pres.save_as_markdown("output.md").unwrap();
/// ```
pub fn save_as_markdown<P: AsRef<Path>>(&self, path: P) -> Result<()> {
use crate::export::md::export_to_markdown;
let md = export_to_markdown(self)?;
std::fs::write(path, md)?;
Ok(())
}
/// Export the presentation to Markdown with custom options
pub fn save_as_markdown_with_options<P: AsRef<Path>>(
&self,
path: P,
options: &crate::export::md::MarkdownOptions,
) -> Result<()> {
use crate::export::md::export_to_markdown_with_options;
let md = export_to_markdown_with_options(self, options)?;
std::fs::write(path, md)?;
Ok(())
}
/// Export slides to image files (PNG/JPEG)
///
/// Uses LibreOffice for rendering. Requires LibreOffice to be installed.
///
/// # Arguments
/// * `output_dir` - Directory to save images
/// * `options` - Image export options (format, DPI, quality)
///
/// # Returns
/// Vector of paths to generated image files
pub fn save_as_images<P: AsRef<Path>>(
&self,
output_dir: P,
options: &crate::export::image_export::ImageExportOptions,
) -> Result<Vec<std::path::PathBuf>> {
use crate::export::image_export::export_to_images;
export_to_images(self, output_dir, options)
}
/// Export a specific slide to an image file
///
/// # Arguments
/// * `slide_number` - 1-based slide number
/// * `output_path` - Output file path
/// * `options` - Image export options
pub fn save_slide_as_image<P: AsRef<Path>>(
&self,
slide_number: usize,
output_path: P,
options: &crate::export::image_export::ImageExportOptions,
) -> Result<std::path::PathBuf> {
use crate::export::image_export::export_slide_to_image;
export_slide_to_image(self, slide_number, output_path, options)
}
/// Render a thumbnail of the first slide
///
/// # Arguments
/// * `output_path` - Output file path
/// * `width` - Desired width in pixels
pub fn save_thumbnail<P: AsRef<Path>>(&self, output_path: P, width: u32) -> Result<std::path::PathBuf> {
use crate::export::image_export::render_thumbnail;
render_thumbnail(self, output_path, width)
}
/// Compress and optimize the presentation
///
/// Saves a compressed version with reduced file size.
///
/// # Arguments
/// * `output_path` - Path for compressed PPTX file
/// * `options` - Compression options (level, features to remove)
///
/// # Returns
/// Compression result with statistics
///
/// # Example
/// ```
/// # use ppt_rs::api::Presentation;
/// # use ppt_rs::opc::compress::CompressionOptions;
/// # let pres = Presentation::with_title("Large Presentation");
/// # let options = CompressionOptions::web();
/// # // let result = pres.compress("optimized.pptx", &options).unwrap();
/// # // println!("Reduced by {:.1}%", result.reduction_percent);
/// ```
pub fn compress<P: AsRef<Path>>(
&self,
output_path: P,
options: &crate::opc::compress::CompressionOptions,
) -> Result<crate::opc::compress::CompressionResult> {
// First save to temp file
let temp_dir = std::env::temp_dir();
let temp_path = temp_dir.join(format!("compress_{}.pptx", uuid::Uuid::new_v4()));
self.save(&temp_path)?;
// Compress
let result = crate::opc::compress::compress_pptx(&temp_path, output_path, options);
// Cleanup
let _ = std::fs::remove_file(&temp_path);
result
}
/// Get file size analysis
///
/// Returns analysis of what contributes to file size.
pub fn analyze_size(&self) -> Result<crate::opc::compress::PptxAnalysis> {
// Save to temp file for analysis
let temp_dir = std::env::temp_dir();
let temp_path = temp_dir.join(format!("analyze_{}.pptx", uuid::Uuid::new_v4()));
self.save(&temp_path)?;
let analysis = crate::opc::compress::analyze_pptx(&temp_path);
// Cleanup
let _ = std::fs::remove_file(&temp_path);
analysis
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_presentation_builder() {
let pres = Presentation::with_title("Test")
.add_slide(SlideContent::new("Slide 1").add_bullet("Point 1"));
assert_eq!(pres.get_title(), "Test");
assert_eq!(pres.slide_count(), 1);
}
#[test]
fn test_presentation_build() {
let pres = Presentation::with_title("Test").add_slide(SlideContent::new("Slide 1"));
let result = pres.build();
assert!(result.is_ok());
}
}