pdf_oxide 0.3.22

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
//! Pattern support for PDF generation.
//!
//! This module provides builders for PDF pattern resources:
//! - Tiling patterns (Type 1) - repeating content
//! - Shading patterns (Type 2) - gradient-based patterns
//!
//! # Example
//!
//! ```ignore
//! use pdf_oxide::writer::pattern::{TilingPatternBuilder, PatternPaintType};
//! use pdf_oxide::layout::Color;
//!
//! // Create a striped pattern
//! let pattern = TilingPatternBuilder::new()
//!     .bbox(0.0, 0.0, 10.0, 10.0)
//!     .x_step(10.0)
//!     .y_step(10.0)
//!     .colored()
//!     .content(|builder| {
//!         builder
//!             .set_fill_color(1.0, 0.0, 0.0)
//!             .rect(0.0, 0.0, 5.0, 10.0)
//!             .fill();
//!     })
//!     .build();
//! ```

use crate::layout::Color;
use crate::object::Object;
use std::collections::HashMap;

/// Helper to create a string key for dictionary
fn key(s: &str) -> String {
    s.to_string()
}

/// Pattern paint type.
#[derive(Debug, Clone, Copy, Default)]
pub enum PatternPaintType {
    /// Colored pattern - colors specified in pattern content
    #[default]
    Colored = 1,
    /// Uncolored pattern - color specified when pattern is used
    Uncolored = 2,
}

/// Pattern tiling type.
#[derive(Debug, Clone, Copy, Default)]
pub enum PatternTilingType {
    /// Constant spacing - pattern cell spacing is constant
    #[default]
    ConstantSpacing = 1,
    /// No distortion - cell is adjusted to device pixels without distortion
    NoDistortion = 2,
    /// Constant spacing and faster tiling
    ConstantSpacingFaster = 3,
}

/// Builder for tiling patterns (Type 1).
///
/// Tiling patterns paint a cell that is replicated at fixed intervals
/// to fill the area to be painted.
#[derive(Debug, Clone)]
pub struct TilingPatternBuilder {
    /// Bounding box of the pattern cell
    bbox: (f32, f32, f32, f32),
    /// Horizontal spacing between pattern cells
    x_step: f32,
    /// Vertical spacing between pattern cells
    y_step: f32,
    /// Paint type
    paint_type: PatternPaintType,
    /// Tiling type
    tiling_type: PatternTilingType,
    /// Pattern content stream
    content: Vec<u8>,
    /// Pattern matrix (optional transformation)
    matrix: Option<[f32; 6]>,
    /// Resources needed by the pattern
    resources: HashMap<Vec<u8>, Object>,
}

impl Default for TilingPatternBuilder {
    fn default() -> Self {
        Self {
            bbox: (0.0, 0.0, 10.0, 10.0),
            x_step: 10.0,
            y_step: 10.0,
            paint_type: PatternPaintType::Colored,
            tiling_type: PatternTilingType::ConstantSpacing,
            content: Vec::new(),
            matrix: None,
            resources: HashMap::new(),
        }
    }
}

impl TilingPatternBuilder {
    /// Create a new tiling pattern builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the bounding box of the pattern cell.
    pub fn bbox(mut self, x: f32, y: f32, width: f32, height: f32) -> Self {
        self.bbox = (x, y, width, height);
        self
    }

    /// Set the horizontal step (spacing).
    pub fn x_step(mut self, step: f32) -> Self {
        self.x_step = step;
        self
    }

    /// Set the vertical step (spacing).
    pub fn y_step(mut self, step: f32) -> Self {
        self.y_step = step;
        self
    }

    /// Set both steps at once.
    pub fn step(self, x: f32, y: f32) -> Self {
        self.x_step(x).y_step(y)
    }

    /// Set as colored pattern (colors in pattern content).
    pub fn colored(mut self) -> Self {
        self.paint_type = PatternPaintType::Colored;
        self
    }

    /// Set as uncolored pattern (color specified at use time).
    pub fn uncolored(mut self) -> Self {
        self.paint_type = PatternPaintType::Uncolored;
        self
    }

    /// Set the tiling type.
    pub fn tiling_type(mut self, tiling: PatternTilingType) -> Self {
        self.tiling_type = tiling;
        self
    }

    /// Set the pattern transformation matrix.
    pub fn matrix(mut self, a: f32, b: f32, c: f32, d: f32, e: f32, f: f32) -> Self {
        self.matrix = Some([a, b, c, d, e, f]);
        self
    }

    /// Set the raw content stream.
    pub fn content_bytes(mut self, content: Vec<u8>) -> Self {
        self.content = content;
        self
    }

    /// Build the pattern dictionary and content stream.
    ///
    /// Returns (dictionary, content_stream_bytes).
    pub fn build(&self) -> (Object, Vec<u8>) {
        let mut dict: HashMap<String, Object> = HashMap::new();

        // Type is always Pattern
        dict.insert(key("Type"), Object::Name("Pattern".to_string()));

        // PatternType 1 = Tiling
        dict.insert(key("PatternType"), Object::Integer(1));

        // PaintType
        dict.insert(key("PaintType"), Object::Integer(self.paint_type as i64));

        // TilingType
        dict.insert(key("TilingType"), Object::Integer(self.tiling_type as i64));

        // BBox
        dict.insert(
            key("BBox"),
            Object::Array(vec![
                Object::Real(self.bbox.0 as f64),
                Object::Real(self.bbox.1 as f64),
                Object::Real(self.bbox.2 as f64),
                Object::Real(self.bbox.3 as f64),
            ]),
        );

        // XStep and YStep
        dict.insert(key("XStep"), Object::Real(self.x_step as f64));
        dict.insert(key("YStep"), Object::Real(self.y_step as f64));

        // Matrix (optional)
        if let Some(m) = &self.matrix {
            dict.insert(
                key("Matrix"),
                Object::Array(m.iter().map(|&v| Object::Real(v as f64)).collect()),
            );
        }

        // Resources (if needed) - convert keys
        if !self.resources.is_empty() {
            let converted: HashMap<String, Object> = self
                .resources
                .iter()
                .map(|(k, v)| (String::from_utf8_lossy(k).to_string(), v.clone()))
                .collect();
            dict.insert(key("Resources"), Object::Dictionary(converted));
        }

        (Object::Dictionary(dict), self.content.clone())
    }
}

/// Builder for shading patterns (Type 2).
///
/// Shading patterns use a shading dictionary to define a gradient fill.
#[derive(Debug, Clone, Default)]
pub struct ShadingPatternBuilder {
    /// Reference to shading dictionary (will be indirect reference)
    shading_id: Option<u32>,
    /// Pattern transformation matrix
    matrix: Option<[f32; 6]>,
    /// ExtGState for the pattern
    ext_gstate_id: Option<u32>,
}

impl ShadingPatternBuilder {
    /// Create a new shading pattern builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the shading object ID (will be referenced indirectly).
    pub fn shading_id(mut self, id: u32) -> Self {
        self.shading_id = Some(id);
        self
    }

    /// Set the pattern transformation matrix.
    pub fn matrix(mut self, a: f32, b: f32, c: f32, d: f32, e: f32, f: f32) -> Self {
        self.matrix = Some([a, b, c, d, e, f]);
        self
    }

    /// Set the ExtGState object ID.
    pub fn ext_gstate_id(mut self, id: u32) -> Self {
        self.ext_gstate_id = Some(id);
        self
    }

    /// Build the pattern dictionary.
    pub fn build(&self) -> Object {
        let mut dict: HashMap<String, Object> = HashMap::new();

        // Type is always Pattern
        dict.insert(key("Type"), Object::Name("Pattern".to_string()));

        // PatternType 2 = Shading
        dict.insert(key("PatternType"), Object::Integer(2));

        // Shading (indirect reference) - caller must set this
        // We'll put a placeholder that the caller should replace
        if let Some(id) = self.shading_id {
            dict.insert(key("Shading"), Object::Reference(crate::object::ObjectRef::new(id, 0)));
        }

        // Matrix (optional)
        if let Some(m) = &self.matrix {
            dict.insert(
                key("Matrix"),
                Object::Array(m.iter().map(|&v| Object::Real(v as f64)).collect()),
            );
        }

        // ExtGState (optional)
        if let Some(id) = self.ext_gstate_id {
            dict.insert(key("ExtGState"), Object::Reference(crate::object::ObjectRef::new(id, 0)));
        }

        Object::Dictionary(dict)
    }
}

/// Predefined pattern presets.
pub struct PatternPresets;

impl PatternPresets {
    /// Create horizontal stripes pattern content.
    pub fn horizontal_stripes(
        width: f32,
        _height: f32,
        stripe_height: f32,
        color: Color,
    ) -> Vec<u8> {
        format!(
            "{} {} {} rg\n0 0 {} {} re\nf\n",
            color.r, color.g, color.b, width, stripe_height
        )
        .into_bytes()
    }

    /// Create vertical stripes pattern content.
    pub fn vertical_stripes(_width: f32, height: f32, stripe_width: f32, color: Color) -> Vec<u8> {
        format!(
            "{} {} {} rg\n0 0 {} {} re\nf\n",
            color.r, color.g, color.b, stripe_width, height
        )
        .into_bytes()
    }

    /// Create a checkerboard pattern content.
    pub fn checkerboard(size: f32, color1: Color, color2: Color) -> Vec<u8> {
        format!(
            "{} {} {} rg\n0 0 {} {} re\nf\n{} {} {} rg\n{} 0 {} {} re\n0 {} {} {} re\nf\n",
            color1.r,
            color1.g,
            color1.b,
            size * 2.0,
            size * 2.0,
            color2.r,
            color2.g,
            color2.b,
            size,
            size,
            size,
            size,
            size,
            size
        )
        .into_bytes()
    }

    /// Create a dot pattern content.
    pub fn dots(spacing: f32, radius: f32, color: Color) -> Vec<u8> {
        // Approximate circle with Bézier curves
        let k = radius * 0.552_284_8;
        let cx = spacing / 2.0;
        let cy = spacing / 2.0;

        format!(
            "{} {} {} rg\n\
             {} {} m\n\
             {} {} {} {} {} {} c\n\
             {} {} {} {} {} {} c\n\
             {} {} {} {} {} {} c\n\
             {} {} {} {} {} {} c\n\
             f\n",
            color.r,
            color.g,
            color.b,
            cx + radius,
            cy,
            cx + radius,
            cy + k,
            cx + k,
            cy + radius,
            cx,
            cy + radius,
            cx - k,
            cy + radius,
            cx - radius,
            cy + k,
            cx - radius,
            cy,
            cx - radius,
            cy - k,
            cx - k,
            cy - radius,
            cx,
            cy - radius,
            cx + k,
            cy - radius,
            cx + radius,
            cy - k,
            cx + radius,
            cy
        )
        .into_bytes()
    }

    /// Create diagonal lines pattern content.
    pub fn diagonal_lines(size: f32, line_width: f32, color: Color) -> Vec<u8> {
        format!(
            "{} {} {} RG\n{} w\n0 0 m\n{} {} l\nS\n",
            color.r, color.g, color.b, line_width, size, size
        )
        .into_bytes()
    }

    /// Create a crosshatch pattern content.
    pub fn crosshatch(size: f32, line_width: f32, color: Color) -> Vec<u8> {
        format!(
            "{} {} {} RG\n{} w\n\
             0 0 m\n{} {} l\nS\n\
             {} 0 m\n0 {} l\nS\n",
            color.r, color.g, color.b, line_width, size, size, size, size
        )
        .into_bytes()
    }
}

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

    #[test]
    fn test_tiling_pattern_builder() {
        let content =
            PatternPresets::horizontal_stripes(10.0, 10.0, 5.0, Color::new(1.0, 0.0, 0.0));
        let (dict, _content) = TilingPatternBuilder::new()
            .bbox(0.0, 0.0, 10.0, 10.0)
            .step(10.0, 10.0)
            .colored()
            .content_bytes(content)
            .build();

        if let Object::Dictionary(d) = dict {
            assert!(d.contains_key("PatternType"));
            if let Some(Object::Integer(pt)) = d.get("PatternType") {
                assert_eq!(*pt, 1);
            }
        } else {
            panic!("Expected dictionary");
        }
    }

    #[test]
    fn test_shading_pattern_builder() {
        let dict = ShadingPatternBuilder::new()
            .shading_id(5)
            .matrix(1.0, 0.0, 0.0, 1.0, 0.0, 0.0)
            .build();

        if let Object::Dictionary(d) = dict {
            assert!(d.contains_key("PatternType"));
            if let Some(Object::Integer(pt)) = d.get("PatternType") {
                assert_eq!(*pt, 2);
            }
        } else {
            panic!("Expected dictionary");
        }
    }

    #[test]
    fn test_pattern_presets() {
        let _ = PatternPresets::horizontal_stripes(10.0, 10.0, 5.0, Color::new(0.0, 0.0, 1.0));
        let _ = PatternPresets::checkerboard(5.0, Color::white(), Color::black());
        let _ = PatternPresets::dots(10.0, 2.0, Color::new(1.0, 0.0, 0.0));
        let _ = PatternPresets::diagonal_lines(10.0, 0.5, Color::black());
    }
}