pdf_oxide 0.3.38

The fastest Rust PDF library with text extraction: 0.8ms mean, 100% pass rate on 3,830 PDFs. 5× faster than pdf_extract, 17× faster than oxidize_pdf. Extract, create, and edit PDFs.
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
//! Page templates for headers, footers, and page numbers.
//!
//! This module provides reusable page templates with placeholder support
//! for adding consistent headers and footers across documents.
//!
//! # Example
//!
//! ```ignore
//! use pdf_oxide::writer::{PageTemplate, Artifact, Placeholder};
//!
//! let template = PageTemplate::new()
//!     .header(Artifact::center("My Document"))
//!     .footer(Artifact::right("{page} of {pages}"));
//! ```

use super::font_manager::FontWeight;

/// Placeholder tokens that can be used in headers and footers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Placeholder {
    /// Current page number (1-indexed)
    PageNumber,
    /// Total number of pages
    TotalPages,
    /// Current date (formatted as YYYY-MM-DD)
    Date,
    /// Current time (formatted as HH:MM)
    Time,
    /// Document title (from metadata)
    Title,
    /// Document author (from metadata)
    Author,
}

impl Placeholder {
    /// Get the placeholder token string.
    pub fn token(&self) -> &'static str {
        match self {
            Placeholder::PageNumber => "{page}",
            Placeholder::TotalPages => "{pages}",
            Placeholder::Date => "{date}",
            Placeholder::Time => "{time}",
            Placeholder::Title => "{title}",
            Placeholder::Author => "{author}",
        }
    }

    /// Parse placeholder tokens from a string.
    pub fn parse_all(text: &str) -> Vec<(usize, Placeholder)> {
        let mut placeholders = Vec::new();

        for ph in [
            Placeholder::PageNumber,
            Placeholder::TotalPages,
            Placeholder::Date,
            Placeholder::Time,
            Placeholder::Title,
            Placeholder::Author,
        ] {
            let token = ph.token();
            let mut start = 0;
            while let Some(pos) = text[start..].find(token) {
                placeholders.push((start + pos, ph));
                start += pos + token.len();
            }
        }

        // Sort by position
        placeholders.sort_by_key(|(pos, _)| *pos);
        placeholders
    }
}

/// Text alignment for header/footer content.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ArtifactAlignment {
    /// Align to the left margin
    Left,
    /// Center horizontally
    #[default]
    Center,
    /// Align to the right margin
    Right,
}

/// Style configuration for header/footer text.
#[derive(Debug, Clone)]
pub struct ArtifactStyle {
    /// Font name
    pub font_name: String,
    /// Font size in points
    pub font_size: f32,
    /// Font weight
    pub font_weight: FontWeight,
    /// Text color (RGB, 0.0-1.0)
    pub color: (f32, f32, f32),
    /// Whether to draw a separator line
    pub separator_line: bool,
    /// Separator line width
    pub separator_width: f32,
}

impl Default for ArtifactStyle {
    fn default() -> Self {
        Self {
            font_name: "Helvetica".to_string(),
            font_size: 10.0,
            font_weight: FontWeight::Normal,
            color: (0.0, 0.0, 0.0), // Black
            separator_line: false,
            separator_width: 0.5,
        }
    }
}

impl ArtifactStyle {
    /// Create a new default style.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the font.
    pub fn font(mut self, name: impl Into<String>, size: f32) -> Self {
        self.font_name = name.into();
        self.font_size = size;
        self
    }

    /// Set bold weight.
    pub fn bold(mut self) -> Self {
        self.font_weight = FontWeight::Bold;
        self
    }

    /// Set text color.
    pub fn color(mut self, r: f32, g: f32, b: f32) -> Self {
        self.color = (r, g, b);
        self
    }

    /// Enable separator line.
    pub fn with_separator(mut self, width: f32) -> Self {
        self.separator_line = true;
        self.separator_width = width;
        self
    }
}

/// A single positioned text element in a header or footer.
#[derive(Debug, Clone)]
pub struct ArtifactElement {
    /// The text content (may include placeholders)
    pub text: String,
    /// Horizontal alignment
    pub alignment: ArtifactAlignment,
    /// Style for this element
    pub style: Option<ArtifactStyle>,
}

impl ArtifactElement {
    /// Create a new element with default center alignment.
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            alignment: ArtifactAlignment::Center,
            style: None,
        }
    }

    /// Create a left-aligned element.
    pub fn left(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            alignment: ArtifactAlignment::Left,
            style: None,
        }
    }

    /// Create a center-aligned element.
    pub fn center(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            alignment: ArtifactAlignment::Center,
            style: None,
        }
    }

    /// Create a right-aligned element.
    pub fn right(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            alignment: ArtifactAlignment::Right,
            style: None,
        }
    }

    /// Set the style for this element.
    pub fn with_style(mut self, style: ArtifactStyle) -> Self {
        self.style = Some(style);
        self
    }

    /// Resolve placeholders in the text.
    pub fn resolve(&self, context: &PlaceholderContext) -> String {
        let mut result = self.text.clone();

        result = result.replace(Placeholder::PageNumber.token(), &context.page_number.to_string());
        result = result.replace(Placeholder::TotalPages.token(), &context.total_pages.to_string());
        result = result.replace(Placeholder::Date.token(), &context.date);
        result = result.replace(Placeholder::Time.token(), &context.time);
        result = result.replace(Placeholder::Title.token(), &context.title);
        result = result.replace(Placeholder::Author.token(), &context.author);

        result
    }
}

/// A header or footer artifact definition.
#[derive(Debug, Clone, Default)]
pub struct Artifact {
    /// Left-aligned element
    pub left: Option<ArtifactElement>,
    /// Center-aligned element
    pub center: Option<ArtifactElement>,
    /// Right-aligned element
    pub right: Option<ArtifactElement>,
    /// Default style for all elements
    pub style: ArtifactStyle,
    /// Vertical offset from page edge (points)
    pub offset: f32,
}

/// Alias for Header
pub type Header = Artifact;
/// Alias for Footer
pub type Footer = Artifact;

impl Artifact {
    /// Create a new empty artifact.
    pub fn new() -> Self {
        Self {
            offset: 36.0, // Half inch from edge
            ..Default::default()
        }
    }

    /// Create with a single left-aligned element.
    pub fn left(text: impl Into<String>) -> Self {
        let mut hf = Self::new();
        hf.left = Some(ArtifactElement::left(text));
        hf
    }

    /// Create with a single centered element.
    pub fn center(text: impl Into<String>) -> Self {
        let mut hf = Self::new();
        hf.center = Some(ArtifactElement::center(text));
        hf
    }

    /// Create with a single right-aligned element.
    pub fn right(text: impl Into<String>) -> Self {
        let mut hf = Self::new();
        hf.right = Some(ArtifactElement::right(text));
        hf
    }

    /// Set the left element.
    pub fn with_left(mut self, text: impl Into<String>) -> Self {
        self.left = Some(ArtifactElement::left(text));
        self
    }

    /// Set the center element.
    pub fn with_center(mut self, text: impl Into<String>) -> Self {
        self.center = Some(ArtifactElement::center(text));
        self
    }

    /// Set the right element.
    pub fn with_right(mut self, text: impl Into<String>) -> Self {
        self.right = Some(ArtifactElement::right(text));
        self
    }

    /// Set the default style.
    pub fn with_style(mut self, style: ArtifactStyle) -> Self {
        self.style = style;
        self
    }

    /// Set the offset from page edge.
    pub fn with_offset(mut self, offset: f32) -> Self {
        self.offset = offset;
        self
    }

    /// Check if this header/footer has any content.
    pub fn is_empty(&self) -> bool {
        self.left.is_none() && self.center.is_none() && self.right.is_none()
    }

    /// Get all elements as positioned items.
    pub fn elements(&self) -> Vec<&ArtifactElement> {
        let mut elements = Vec::new();
        if let Some(ref e) = self.left {
            elements.push(e);
        }
        if let Some(ref e) = self.center {
            elements.push(e);
        }
        if let Some(ref e) = self.right {
            elements.push(e);
        }
        elements
    }
}

/// Context for resolving placeholders.
#[derive(Debug, Clone)]
pub struct PlaceholderContext {
    /// Current page number (1-indexed)
    pub page_number: usize,
    /// Total number of pages
    pub total_pages: usize,
    /// Current date
    pub date: String,
    /// Current time
    pub time: String,
    /// Document title
    pub title: String,
    /// Document author
    pub author: String,
}

impl PlaceholderContext {
    /// Create a new context with current date/time.
    pub fn new(page_number: usize, total_pages: usize) -> Self {
        let now = chrono::Local::now();
        Self {
            page_number,
            total_pages,
            date: now.format("%Y-%m-%d").to_string(),
            time: now.format("%H:%M").to_string(),
            title: String::new(),
            author: String::new(),
        }
    }

    /// Set the document title.
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = title.into();
        self
    }

    /// Set the document author.
    pub fn with_author(mut self, author: impl Into<String>) -> Self {
        self.author = author.into();
        self
    }
}

impl Default for PlaceholderContext {
    fn default() -> Self {
        Self::new(1, 1)
    }
}

/// A complete page template with header and footer.
#[derive(Debug, Clone, Default)]
pub struct PageTemplate {
    /// Header definition
    pub header: Option<Artifact>,
    /// Footer definition
    pub footer: Option<Artifact>,
    /// Whether to skip header/footer on first page
    pub skip_first_page: bool,
    /// Optional different template for first page
    pub first_page_header: Option<Artifact>,
    /// Optional different footer for first page
    pub first_page_footer: Option<Artifact>,
    /// Left margin (points)
    pub margin_left: f32,
    /// Right margin (points)
    pub margin_right: f32,
}

impl PageTemplate {
    /// Create a new empty page template.
    pub fn new() -> Self {
        Self {
            margin_left: 72.0,  // 1 inch
            margin_right: 72.0, // 1 inch
            ..Default::default()
        }
    }

    /// Set the header.
    pub fn header(mut self, header: Artifact) -> Self {
        self.header = Some(header);
        self
    }

    /// Set the footer.
    pub fn footer(mut self, footer: Artifact) -> Self {
        self.footer = Some(footer);
        self
    }

    /// Set to skip header/footer on first page.
    pub fn skip_first_page(mut self) -> Self {
        self.skip_first_page = true;
        self
    }

    /// Set a different header for the first page.
    pub fn first_page_header(mut self, header: Artifact) -> Self {
        self.first_page_header = Some(header);
        self
    }

    /// Set a different footer for the first page.
    pub fn first_page_footer(mut self, footer: Artifact) -> Self {
        self.first_page_footer = Some(footer);
        self
    }

    /// Set margins.
    pub fn margins(mut self, left: f32, right: f32) -> Self {
        self.margin_left = left;
        self.margin_right = right;
        self
    }

    /// Get the header for a specific page.
    pub fn get_header(&self, page_number: usize) -> Option<&Artifact> {
        if page_number == 1 {
            if self.skip_first_page && self.first_page_header.is_none() {
                return None;
            }
            self.first_page_header.as_ref().or(self.header.as_ref())
        } else {
            self.header.as_ref()
        }
    }

    /// Get the footer for a specific page.
    pub fn get_footer(&self, page_number: usize) -> Option<&Artifact> {
        if page_number == 1 {
            if self.skip_first_page && self.first_page_footer.is_none() {
                return None;
            }
            self.first_page_footer.as_ref().or(self.footer.as_ref())
        } else {
            self.footer.as_ref()
        }
    }

    /// Check if the template has any content.
    pub fn is_empty(&self) -> bool {
        self.header.is_none()
            && self.footer.is_none()
            && self.first_page_header.is_none()
            && self.first_page_footer.is_none()
    }
}

/// Common page number format patterns.
pub struct PageNumberFormat;

impl PageNumberFormat {
    /// "Page X" format
    pub fn page_x() -> String {
        "Page {page}".to_string()
    }

    /// "Page X of Y" format
    pub fn page_x_of_y() -> String {
        "Page {page} of {pages}".to_string()
    }

    /// "X / Y" format
    pub fn x_slash_y() -> String {
        "{page} / {pages}".to_string()
    }

    /// "X" format (just the number)
    pub fn number_only() -> String {
        "{page}".to_string()
    }

    /// "- X -" format
    pub fn dashed() -> String {
        "- {page} -".to_string()
    }
}

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

    #[test]
    fn test_placeholder_tokens() {
        assert_eq!(Placeholder::PageNumber.token(), "{page}");
        assert_eq!(Placeholder::TotalPages.token(), "{pages}");
        assert_eq!(Placeholder::Date.token(), "{date}");
    }

    #[test]
    fn test_placeholder_parse() {
        let text = "Page {page} of {pages}";
        let placeholders = Placeholder::parse_all(text);

        assert_eq!(placeholders.len(), 2);
        assert_eq!(placeholders[0].1, Placeholder::PageNumber);
        assert_eq!(placeholders[1].1, Placeholder::TotalPages);
    }

    #[test]
    fn test_hf_element_resolve() {
        let element = ArtifactElement::center("Page {page} of {pages}");
        let context = PlaceholderContext::new(5, 10);

        let resolved = element.resolve(&context);
        assert_eq!(resolved, "Page 5 of 10");
    }

    #[test]
    fn test_artifact_creation() {
        let hf = Artifact::new()
            .with_left("Document Title")
            .with_right("{page}");

        assert!(hf.left.is_some());
        assert!(hf.center.is_none());
        assert!(hf.right.is_some());
    }

    #[test]
    fn test_page_template() {
        let template = PageTemplate::new()
            .header(Artifact::center("My Document"))
            .footer(Artifact::right("{page} of {pages}"));

        assert!(template.header.is_some());
        assert!(template.footer.is_some());
        assert!(!template.is_empty());
    }

    #[test]
    fn test_skip_first_page() {
        let template = PageTemplate::new()
            .header(Artifact::center("Header"))
            .skip_first_page();

        assert!(template.get_header(1).is_none());
        assert!(template.get_header(2).is_some());
    }

    #[test]
    fn test_first_page_template() {
        let template = PageTemplate::new()
            .header(Artifact::center("Regular Header"))
            .first_page_header(Artifact::center("Title Page"));

        let first = template.get_header(1).unwrap();
        let second = template.get_header(2).unwrap();

        assert_eq!(first.center.as_ref().unwrap().text, "Title Page");
        assert_eq!(second.center.as_ref().unwrap().text, "Regular Header");
    }

    #[test]
    fn test_page_number_formats() {
        assert_eq!(PageNumberFormat::page_x(), "Page {page}");
        assert_eq!(PageNumberFormat::page_x_of_y(), "Page {page} of {pages}");
        assert_eq!(PageNumberFormat::x_slash_y(), "{page} / {pages}");
    }

    #[test]
    fn test_hf_style() {
        let style = ArtifactStyle::new()
            .font("Times-Roman", 12.0)
            .bold()
            .color(0.5, 0.5, 0.5)
            .with_separator(1.0);

        assert_eq!(style.font_name, "Times-Roman");
        assert_eq!(style.font_size, 12.0);
        assert!(matches!(style.font_weight, FontWeight::Bold));
        assert!(style.separator_line);
    }

    #[test]
    fn test_placeholder_context_with_metadata() {
        let context = PlaceholderContext::new(1, 10)
            .with_title("My Document")
            .with_author("John Doe");

        let element = ArtifactElement::center("{title} by {author}");
        let resolved = element.resolve(&context);

        assert_eq!(resolved, "My Document by John Doe");
    }
}