printwell-pdf 0.1.10

PDF manipulation features (forms, signing) for Printwell
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
//! PDF watermark support.
//!
//! This module provides functionality for adding text and image watermarks
//! to PDF documents using `PDFium` via FFI.
//!
//! # Example
//!
//! ```ignore
//! use printwell_pdf::watermark::{add_watermark, Watermark, Position, Layer};
//!
//! let watermark = Watermark::builder()
//!     .text("CONFIDENTIAL")
//!     .opacity(0.3)
//!     .rotation(45.0)
//!     .color(Color::red())
//!     .position(Position::Center)
//!     .layer(Layer::Background)
//!     .build();
//!
//! let result = add_watermark(&pdf_data, &watermark)?;
//! ```

use crate::Result;
use typed_builder::TypedBuilder;

/// Position of the watermark on the page
#[derive(Debug, Clone, Copy, Default)]
pub enum Position {
    /// Center of the page
    #[default]
    Center,
    /// Top-left corner
    TopLeft,
    /// Top-center
    TopCenter,
    /// Top-right corner
    TopRight,
    /// Middle-left
    MiddleLeft,
    /// Middle-right
    MiddleRight,
    /// Bottom-left corner
    BottomLeft,
    /// Bottom-center
    BottomCenter,
    /// Bottom-right corner
    BottomRight,
    /// Custom position (x, y) in PDF points from bottom-left
    Custom(f32, f32),
}

impl Position {
    /// Get (x, y) position for given page dimensions
    #[must_use]
    pub fn to_coords(
        &self,
        page_width: f32,
        page_height: f32,
        watermark_width: f32,
        watermark_height: f32,
    ) -> (f32, f32) {
        let margin = 36.0; // 0.5 inch margin
        match self {
            Self::Center => (
                (page_width - watermark_width) / 2.0,
                (page_height - watermark_height) / 2.0,
            ),
            Self::TopLeft => (margin, page_height - watermark_height - margin),
            Self::TopCenter => (
                (page_width - watermark_width) / 2.0,
                page_height - watermark_height - margin,
            ),
            Self::TopRight => (
                page_width - watermark_width - margin,
                page_height - watermark_height - margin,
            ),
            Self::MiddleLeft => (margin, (page_height - watermark_height) / 2.0),
            Self::MiddleRight => (
                page_width - watermark_width - margin,
                (page_height - watermark_height) / 2.0,
            ),
            Self::BottomLeft => (margin, margin),
            Self::BottomCenter => ((page_width - watermark_width) / 2.0, margin),
            Self::BottomRight => (page_width - watermark_width - margin, margin),
            Self::Custom(x, y) => (*x, *y),
        }
    }
}

/// Layer where the watermark should be placed
#[derive(Debug, Clone, Copy, Default)]
pub enum Layer {
    /// Behind the page content (background)
    #[default]
    Background,
    /// In front of the page content (foreground)
    Foreground,
}

/// Page selection for watermarking
#[derive(Debug, Clone, Default)]
pub enum PageSelection {
    /// All pages
    #[default]
    All,
    /// Specific page numbers (1-indexed)
    Pages(Vec<u32>),
    /// Page range (start..=end, 1-indexed)
    Range(u32, u32),
    /// Only odd pages
    Odd,
    /// Only even pages
    Even,
    /// First page only
    First,
    /// Last page only
    Last,
}

impl PageSelection {
    /// Check if a page number should be watermarked
    #[must_use]
    pub fn includes(&self, page: u32, total_pages: u32) -> bool {
        match self {
            Self::All => true,
            Self::Pages(pages) => pages.contains(&page),
            Self::Range(start, end) => page >= *start && page <= *end,
            Self::Odd => page % 2 == 1,
            Self::Even => page.is_multiple_of(2),
            Self::First => page == 1,
            Self::Last => page == total_pages,
        }
    }
}

/// RGBA color
#[derive(Debug, Clone, Copy)]
pub struct Color {
    /// Red component (0-255)
    pub r: u8,
    /// Green component (0-255)
    pub g: u8,
    /// Blue component (0-255)
    pub b: u8,
    /// Alpha component (0-255)
    pub a: u8,
}

impl Color {
    /// Create a new color
    #[must_use]
    pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
        Self { r, g, b, a }
    }

    /// Create from RGB (alpha = 255)
    #[must_use]
    pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
        Self { r, g, b, a: 255 }
    }

    /// Parse from hex string (e.g., "#FF0000" or "FF0000")
    #[must_use]
    pub fn from_hex(hex: &str) -> Option<Self> {
        let hex = hex.trim_start_matches('#');
        if hex.len() == 6 {
            let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
            let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
            let b = u8::from_str_radix(&hex[4..6], 16).ok()?;
            Some(Self::rgb(r, g, b))
        } else if hex.len() == 8 {
            let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
            let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
            let b = u8::from_str_radix(&hex[4..6], 16).ok()?;
            let a = u8::from_str_radix(&hex[6..8], 16).ok()?;
            Some(Self::new(r, g, b, a))
        } else {
            None
        }
    }

    /// Red color
    #[must_use]
    pub const fn red() -> Self {
        Self::rgb(255, 0, 0)
    }

    /// Green color
    #[must_use]
    pub const fn green() -> Self {
        Self::rgb(0, 128, 0)
    }

    /// Blue color
    #[must_use]
    pub const fn blue() -> Self {
        Self::rgb(0, 0, 255)
    }

    /// Black color
    #[must_use]
    pub const fn black() -> Self {
        Self::rgb(0, 0, 0)
    }

    /// White color
    #[must_use]
    pub const fn white() -> Self {
        Self::rgb(255, 255, 255)
    }

    /// Gray color
    #[must_use]
    pub const fn gray() -> Self {
        Self::rgb(128, 128, 128)
    }

    /// Convert to u32 ARGB
    #[must_use]
    pub const fn to_argb(&self) -> u32 {
        ((self.a as u32) << 24) | ((self.r as u32) << 16) | ((self.g as u32) << 8) | (self.b as u32)
    }
}

impl Default for Color {
    fn default() -> Self {
        Self::gray()
    }
}

/// Watermark definition
#[derive(Debug, Clone, TypedBuilder)]
pub struct Watermark {
    /// Text content (mutually exclusive with image)
    #[builder(default, setter(into, strip_option))]
    pub text: Option<String>,

    /// Image data (PNG/JPEG bytes, mutually exclusive with text)
    #[builder(default, setter(strip_option))]
    pub image: Option<Vec<u8>>,

    /// Position on the page
    #[builder(default)]
    pub position: Position,

    /// Rotation in degrees (counter-clockwise)
    #[builder(default = 0.0)]
    pub rotation: f32,

    /// Opacity (0.0 = fully transparent, 1.0 = fully opaque)
    #[builder(default = 0.5)]
    pub opacity: f32,

    /// Font size for text watermarks (in points)
    #[builder(default = 72.0)]
    pub font_size: f32,

    /// Font name for text watermarks
    #[builder(default = "Helvetica".into(), setter(into))]
    pub font_name: String,

    /// Color for text watermarks
    #[builder(default)]
    pub color: Color,

    /// Layer (background or foreground)
    #[builder(default)]
    pub layer: Layer,

    /// Which pages to watermark
    #[builder(default)]
    pub pages: PageSelection,

    /// Scale factor for the watermark (1.0 = original size)
    #[builder(default = 1.0)]
    pub scale: f32,
}

impl Watermark {
    /// Check if this is a text watermark
    #[must_use]
    pub const fn is_text(&self) -> bool {
        self.text.is_some()
    }

    /// Check if this is an image watermark
    #[must_use]
    pub const fn is_image(&self) -> bool {
        self.image.is_some()
    }
}

/// Add a watermark to a PDF document.
///
/// This function uses `PDFium` via FFI to add a watermark to each page
/// of the PDF document.
///
/// # Arguments
/// * `pdf_data` - The input PDF data
/// * `watermark` - The watermark configuration
///
/// # Returns
/// The modified PDF data with the watermark applied.
///
/// # Errors
///
/// Returns an error if the watermark is invalid or cannot be added.
pub fn add_watermark(pdf_data: &[u8], watermark: &Watermark) -> Result<Vec<u8>> {
    // Validate watermark
    if watermark.text.is_none() && watermark.image.is_none() {
        return Err(crate::WatermarkError::NoContent.into());
    }
    if watermark.text.is_some() && watermark.image.is_some() {
        return Err(crate::WatermarkError::BothContentTypes.into());
    }
    if watermark.opacity < 0.0 || watermark.opacity > 1.0 {
        return Err(crate::WatermarkError::InvalidOpacity {
            value: watermark.opacity,
        }
        .into());
    }

    // Convert to FFI watermark definition
    let wm_def = printwell_sys::WatermarkDef {
        text: watermark.text.clone().unwrap_or_default(),
        image: watermark.image.clone().unwrap_or_default(),
        x: 0.0, // Calculated per-page
        y: 0.0,
        rotation: watermark.rotation,
        opacity: watermark.opacity,
        font_size: watermark.font_size,
        font_name: watermark.font_name.clone(),
        color: watermark.color.to_argb(),
        behind_content: matches!(watermark.layer, Layer::Background),
        // Page selection is handled in the FFI layer
        pages: match &watermark.pages {
            PageSelection::All => vec![],
            PageSelection::Pages(pages) => pages
                .iter()
                .map(|&p| i32::try_from(p).unwrap_or(i32::MAX))
                .collect(),
            PageSelection::Range(start, end) => (*start..=*end)
                .map(|p| i32::try_from(p).unwrap_or(i32::MAX))
                .collect(),
            PageSelection::Odd => vec![-1], // Special marker
            PageSelection::Even => vec![-2],
            PageSelection::First => vec![-3],
            PageSelection::Last => vec![-4],
        },
        position_type: match watermark.position {
            Position::Center => 0,
            Position::TopLeft => 1,
            Position::TopCenter => 2,
            Position::TopRight => 3,
            Position::MiddleLeft => 4,
            Position::MiddleRight => 5,
            Position::BottomLeft => 6,
            Position::BottomCenter => 7,
            Position::BottomRight => 8,
            Position::Custom(_, _) => 9,
        },
        custom_x: match watermark.position {
            Position::Custom(x, _) => x,
            _ => 0.0,
        },
        custom_y: match watermark.position {
            Position::Custom(_, y) => y,
            _ => 0.0,
        },
        scale: watermark.scale,
    };

    // Call FFI function
    let result = printwell_sys::ffi::pdf_add_watermark(pdf_data, &wm_def)
        .map_err(|e| crate::WatermarkError::AddFailed(e.to_string()))?;

    Ok(result)
}

/// Add multiple watermarks to a PDF document.
///
/// # Errors
///
/// Returns an error if any watermark is invalid or cannot be added.
pub fn add_watermarks(pdf_data: &[u8], watermarks: &[Watermark]) -> Result<Vec<u8>> {
    let mut result = pdf_data.to_vec();
    for watermark in watermarks {
        result = add_watermark(&result, watermark)?;
    }
    Ok(result)
}

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

    #[test]
    fn test_position_to_coords() {
        let pos = Position::Center;
        let (x, y) = pos.to_coords(612.0, 792.0, 100.0, 50.0);
        assert!((x - 256.0).abs() < f32::EPSILON);
        assert!((y - 371.0).abs() < f32::EPSILON);
    }

    #[test]
    fn test_color_from_hex() {
        let color = Color::from_hex("#FF0000").unwrap();
        assert_eq!(color.r, 255);
        assert_eq!(color.g, 0);
        assert_eq!(color.b, 0);

        let color = Color::from_hex("00FF00").unwrap();
        assert_eq!(color.r, 0);
        assert_eq!(color.g, 255);
        assert_eq!(color.b, 0);
    }

    #[test]
    fn test_page_selection() {
        assert!(PageSelection::All.includes(1, 10));
        assert!(PageSelection::All.includes(10, 10));

        assert!(PageSelection::Odd.includes(1, 10));
        assert!(!PageSelection::Odd.includes(2, 10));

        assert!(!PageSelection::Even.includes(1, 10));
        assert!(PageSelection::Even.includes(2, 10));

        assert!(PageSelection::First.includes(1, 10));
        assert!(!PageSelection::First.includes(2, 10));

        assert!(!PageSelection::Last.includes(1, 10));
        assert!(PageSelection::Last.includes(10, 10));

        assert!(PageSelection::Range(3, 5).includes(3, 10));
        assert!(PageSelection::Range(3, 5).includes(4, 10));
        assert!(PageSelection::Range(3, 5).includes(5, 10));
        assert!(!PageSelection::Range(3, 5).includes(2, 10));
        assert!(!PageSelection::Range(3, 5).includes(6, 10));
    }
}