pdfrs 0.1.0

A CLI tool to read/write PDFs and convert to/from markdown
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
//! PDF optimization profiles for different use cases
//!
//! This module provides pre-configured optimization profiles for common scenarios:
//! - Web: Optimized for fast loading and small file size
//! - Print: High quality, larger file size
//! - Archive: Balanced compression and quality
//! - Ebook: Mobile-optimized with moderate compression

use crate::pdf_generator::PageLayout;
use anyhow::Result;

/// Optimization profile for PDF generation
///
/// Each profile defines trade-offs between file size, quality, and performance.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OptimizationProfile {
    /// Web-optimized PDF (smallest file size, moderate quality)
    ///
    /// Best for: websites, email attachments, quick downloads
    /// - Higher compression
    /// - Downsampled images to 150 DPI
    /// - Subset fonts when possible
    /// - Remove metadata
    Web,

    /// Print-optimized PDF (highest quality, larger file size)
    ///
    /// Best for: professional printing, high-quality documents
    /// - Minimal compression
    /// - Images at 300 DPI or higher
    /// - Embed all fonts
    /// - Preserve all metadata
    Print,

    /// Archive-optimized PDF (balanced compression and quality)
    ///
    /// Best for: long-term storage, legal documents, records retention
    /// - Standard compression
    /// - Images at 200-300 DPI
    /// - Embed all fonts
    /// - Preserve all metadata
    Archive,

    /// Ebook-optimized PDF (mobile-friendly, moderate compression)
    ///
    /// Best for: e-readers, tablets, mobile devices
    /// - Moderate compression
    /// - Images at 150-200 DPI
    /// - Embed commonly used fonts
    /// - Tagged PDF for accessibility
    Ebook,

    /// Custom optimization profile with user-defined settings
    Custom(OptimizationSettings),
}

impl OptimizationProfile {
    /// Get the optimization settings for this profile
    pub fn settings(&self) -> OptimizationSettings {
        match self {
            OptimizationProfile::Web => OptimizationSettings {
                compression_level: CompressionLevel::High,
                image_dpi: 150,
                embed_fonts: false,
                subset_fonts: true,
                preserve_metadata: false,
                tagged_pdf: false,
                linearize: true, // Fast web view
            },
            OptimizationProfile::Print => OptimizationSettings {
                compression_level: CompressionLevel::Low,
                image_dpi: 300,
                embed_fonts: true,
                subset_fonts: false,
                preserve_metadata: true,
                tagged_pdf: false,
                linearize: false,
            },
            OptimizationProfile::Archive => OptimizationSettings {
                compression_level: CompressionLevel::Medium,
                image_dpi: 250,
                embed_fonts: true,
                subset_fonts: false,
                preserve_metadata: true,
                tagged_pdf: true,
                linearize: false,
            },
            OptimizationProfile::Ebook => OptimizationSettings {
                compression_level: CompressionLevel::Medium,
                image_dpi: 180,
                embed_fonts: true,
                subset_fonts: false,
                preserve_metadata: true,
                tagged_pdf: true,
                linearize: true,
            },
            OptimizationProfile::Custom(settings) => *settings,
        }
    }

    /// Web-optimized profile
    pub fn web() -> Self {
        OptimizationProfile::Web
    }

    /// Print-optimized profile
    pub fn print() -> Self {
        OptimizationProfile::Print
    }

    /// Archive-optimized profile
    pub fn archive() -> Self {
        OptimizationProfile::Archive
    }

    /// Ebook-optimized profile
    pub fn ebook() -> Self {
        OptimizationProfile::Ebook
    }

    /// Custom profile with specific settings
    pub fn custom(settings: OptimizationSettings) -> Self {
        OptimizationProfile::Custom(settings)
    }
}

impl Default for OptimizationProfile {
    fn default() -> Self {
        OptimizationProfile::Archive
    }
}

/// Detailed optimization settings for PDF generation
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OptimizationSettings {
    /// Compression level for PDF streams
    pub compression_level: CompressionLevel,

    /// Target DPI for images (0 = no downsampling)
    pub image_dpi: u32,

    /// Whether to embed fonts in the PDF
    pub embed_fonts: bool,

    /// Whether to subset fonts (include only used characters)
    pub subset_fonts: bool,

    /// Whether to preserve document metadata
    pub preserve_metadata: bool,

    /// Whether to generate a tagged PDF (accessibility)
    pub tagged_pdf: bool,

    /// Whether to linearize the PDF (fast web view)
    pub linearize: bool,
}

impl Default for OptimizationSettings {
    fn default() -> Self {
        OptimizationProfile::Archive.settings()
    }
}

impl OptimizationSettings {
    /// Create a new OptimizationSettings with sensible defaults
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the compression level
    pub fn with_compression(mut self, level: CompressionLevel) -> Self {
        self.compression_level = level;
        self
    }

    /// Set the target image DPI
    pub fn with_image_dpi(mut self, dpi: u32) -> Self {
        self.image_dpi = dpi;
        self
    }

    /// Set whether to embed fonts
    pub fn with_embed_fonts(mut self, embed: bool) -> Self {
        self.embed_fonts = embed;
        self
    }

    /// Set whether to subset fonts
    pub fn with_subset_fonts(mut self, subset: bool) -> Self {
        self.subset_fonts = subset;
        self
    }

    /// Set whether to preserve metadata
    pub fn with_preserve_metadata(mut self, preserve: bool) -> Self {
        self.preserve_metadata = preserve;
        self
    }

    /// Set whether to generate tagged PDF
    pub fn with_tagged_pdf(mut self, tagged: bool) -> Self {
        self.tagged_pdf = tagged;
        self
    }

    /// Set whether to linearize the PDF
    pub fn with_linearize(mut self, linearize: bool) -> Self {
        self.linearize = linearize;
        self
    }
}

/// Compression level for PDF content streams
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompressionLevel {
    /// No compression (fastest, largest files)
    None,
    /// Low compression (fast, moderately sized files)
    Low,
    /// Medium compression (balanced)
    Medium,
    /// High compression (slower, smallest files)
    High,
    /// Maximum compression (slowest, smallest files)
    Maximum,
}

impl CompressionLevel {
    /// Get the deflate compression level (0-9)
    pub fn deflate_level(&self) -> u8 {
        match self {
            CompressionLevel::None => 0,
            CompressionLevel::Low => 3,
            CompressionLevel::Medium => 6,
            CompressionLevel::High => 9,
            CompressionLevel::Maximum => 9,
        }
    }

    /// No compression
    pub fn none() -> Self {
        CompressionLevel::None
    }

    /// Low compression
    pub fn low() -> Self {
        CompressionLevel::Low
    }

    /// Medium compression
    pub fn medium() -> Self {
        CompressionLevel::Medium
    }

    /// High compression
    pub fn high() -> Self {
        CompressionLevel::High
    }

    /// Maximum compression
    pub fn maximum() -> Self {
        CompressionLevel::Maximum
    }
}

impl Default for CompressionLevel {
    fn default() -> Self {
        CompressionLevel::Medium
    }
}

/// Optimized PDF generator with profile-based settings
pub struct OptimizedPdfGenerator {
    profile: OptimizationProfile,
    settings: OptimizationSettings,
    layout: PageLayout,
    font: String,
    font_size: f32,
}

impl OptimizedPdfGenerator {
    /// Create a new optimized PDF generator with the specified profile
    pub fn new(profile: OptimizationProfile) -> Self {
        let settings = profile.settings();
        Self {
            profile,
            settings,
            layout: PageLayout::portrait(),
            font: "Helvetica".to_string(),
            font_size: 12.0,
        }
    }

    /// Set the page layout
    pub fn with_layout(mut self, layout: PageLayout) -> Self {
        self.layout = layout;
        self
    }

    /// Set the font
    pub fn with_font(mut self, font: &str) -> Self {
        self.font = font.to_string();
        self
    }

    /// Set the font size
    pub fn with_font_size(mut self, size: f32) -> Self {
        self.font_size = size;
        self
    }

    /// Generate a PDF from elements with the current optimization settings
    pub fn generate(&self, elements: &[crate::elements::Element], output_path: &str) -> Result<()> {
        // For now, we'll use the standard generation
        // In a full implementation, we would apply the optimization settings
        crate::pdf_generator::create_pdf_from_elements_with_layout(
            output_path,
            elements,
            &self.font,
            self.font_size,
            self.layout,
        )
    }

    /// Generate a PDF from elements and return the bytes
    pub fn generate_bytes(&self, elements: &[crate::elements::Element]) -> Result<Vec<u8>> {
        // For now, we'll use the standard generation
        // In a full implementation, we would apply the optimization settings
        crate::pdf_generator::generate_pdf_bytes(
            elements,
            &self.font,
            self.font_size,
            self.layout,
        )
    }

    /// Get the current optimization settings
    pub fn settings(&self) -> OptimizationSettings {
        self.settings
    }

    /// Get the current profile
    pub fn profile(&self) -> OptimizationProfile {
        self.profile
    }
}

impl Default for OptimizedPdfGenerator {
    fn default() -> Self {
        Self::new(OptimizationProfile::default())
    }
}

/// Apply optimization settings to existing PDF bytes
///
/// This function re-compresses PDF streams according to the optimization settings.
/// Note: This is a placeholder for a full implementation.
pub fn optimize_pdf_bytes(
    _pdf_data: &[u8],
    _settings: OptimizationSettings,
) -> Result<Vec<u8>> {
    // TODO: Implement full PDF optimization
    // This would involve:
    // - Parsing the PDF
    // - Recompressing streams with the specified compression level
    // - Downsampling images to the target DPI
    // - Subsetting fonts if requested
    // - Removing metadata if not preserving
    // - Linearizing the PDF if requested
    anyhow::bail!("PDF optimization not yet implemented")
}

/// Apply an optimization profile to an existing PDF file
///
/// This is a convenience function that reads a PDF, applies the optimization
/// profile, and writes the result to a new file.
pub fn optimize_pdf_file(
    input_path: &str,
    output_path: &str,
    profile: OptimizationProfile,
) -> Result<()> {
    let data = std::fs::read(input_path)?;
    let optimized = optimize_pdf_bytes(&data, profile.settings())?;
    std::fs::write(output_path, optimized)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_profile_settings() {
        let web_settings = OptimizationProfile::Web.settings();
        assert_eq!(web_settings.compression_level, CompressionLevel::High);
        assert_eq!(web_settings.image_dpi, 150);
        assert!(!web_settings.embed_fonts);
        assert!(web_settings.subset_fonts);
        assert!(web_settings.linearize);

        let print_settings = OptimizationProfile::Print.settings();
        assert_eq!(print_settings.compression_level, CompressionLevel::Low);
        assert_eq!(print_settings.image_dpi, 300);
        assert!(print_settings.embed_fonts);
        assert!(!print_settings.subset_fonts);
        assert!(!print_settings.linearize);
    }

    #[test]
    fn test_custom_settings() {
        let settings = OptimizationSettings::new()
            .with_compression(CompressionLevel::High)
            .with_image_dpi(200)
            .with_embed_fonts(true)
            .with_tagged_pdf(true);

        assert_eq!(settings.compression_level, CompressionLevel::High);
        assert_eq!(settings.image_dpi, 200);
        assert!(settings.embed_fonts);
        assert!(settings.tagged_pdf);
    }

    #[test]
    fn test_compression_level() {
        assert_eq!(CompressionLevel::None.deflate_level(), 0);
        assert_eq!(CompressionLevel::Low.deflate_level(), 3);
        assert_eq!(CompressionLevel::Medium.deflate_level(), 6);
        assert_eq!(CompressionLevel::High.deflate_level(), 9);
        assert_eq!(CompressionLevel::Maximum.deflate_level(), 9);
    }

    #[test]
    fn test_optimized_generator() {
        let generator = OptimizedPdfGenerator::new(OptimizationProfile::Web)
            .with_font("Courier")
            .with_font_size(10.0);

        assert_eq!(generator.profile(), OptimizationProfile::Web);
        assert_eq!(generator.settings().compression_level, CompressionLevel::High);
        assert_eq!(generator.font, "Courier");
        assert_eq!(generator.font_size, 10.0);
    }
}