printwell-pdf 0.1.11

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
//! PDF annotation support.
//!
//! This module provides functionality for adding annotations
//! to PDF documents using `PDFium` via FFI.
//!
//! # Example
//!
//! ```ignore
//! use printwell_pdf::annotations::{add_annotations, Annotation, AnnotationType, Rect, Color};
//!
//! let annotations = vec![
//!     Annotation::builder()
//!         .annotation_type(AnnotationType::Highlight)
//!         .page(1)
//!         .rect(Rect::new(100.0, 700.0, 200.0, 20.0))
//!         .color(Color::yellow())
//!         .build(),
//! ];
//!
//! let result = add_annotations(&pdf_data, &annotations)?;
//! ```

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

/// Annotation types supported by `PDFium`
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnnotationType {
    /// Highlight text markup
    Highlight,
    /// Underline text markup
    Underline,
    /// Strikeout text markup
    Strikeout,
    /// Squiggly underline text markup
    Squiggly,
    /// Sticky note annotation
    Text,
    /// Free text annotation (text box)
    FreeText,
    /// Line annotation
    Line,
    /// Square/rectangle annotation
    Square,
    /// Circle/ellipse annotation
    Circle,
    /// Ink/freehand annotation
    Ink,
    /// Stamp annotation
    Stamp,
    /// Link annotation
    Link,
}

impl AnnotationType {
    /// Convert to `PDFium` annotation type constant
    #[must_use]
    pub const fn to_pdfium_type(&self) -> i32 {
        match self {
            Self::Highlight => 9,  // FPDF_ANNOT_HIGHLIGHT
            Self::Underline => 10, // FPDF_ANNOT_UNDERLINE
            Self::Strikeout => 11, // FPDF_ANNOT_STRIKEOUT
            Self::Squiggly => 12,  // FPDF_ANNOT_SQUIGGLY
            Self::Text => 1,       // FPDF_ANNOT_TEXT
            Self::FreeText => 3,   // FPDF_ANNOT_FREETEXT
            Self::Line => 4,       // FPDF_ANNOT_LINE
            Self::Square => 5,     // FPDF_ANNOT_SQUARE
            Self::Circle => 6,     // FPDF_ANNOT_CIRCLE
            Self::Ink => 15,       // FPDF_ANNOT_INK
            Self::Stamp => 13,     // FPDF_ANNOT_STAMP
            Self::Link => 2,       // FPDF_ANNOT_LINK
        }
    }

    /// Create from `PDFium` annotation type constant
    #[must_use]
    pub const fn from_pdfium_type(t: i32) -> Option<Self> {
        match t {
            9 => Some(Self::Highlight),
            10 => Some(Self::Underline),
            11 => Some(Self::Strikeout),
            12 => Some(Self::Squiggly),
            1 => Some(Self::Text),
            3 => Some(Self::FreeText),
            4 => Some(Self::Line),
            5 => Some(Self::Square),
            6 => Some(Self::Circle),
            15 => Some(Self::Ink),
            13 => Some(Self::Stamp),
            2 => Some(Self::Link),
            _ => None,
        }
    }
}

/// Rectangle for annotation bounds
#[derive(Debug, Clone, Copy, TypedBuilder)]
pub struct Rect {
    /// X coordinate (from left)
    pub x: f32,
    /// Y coordinate (from bottom)
    pub y: f32,
    /// Width
    pub width: f32,
    /// Height
    pub height: f32,
}

impl Rect {
    /// Create a new rectangle
    #[must_use]
    pub const fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }
}

/// Color for annotations
#[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 a color from RGB values (fully opaque)
    #[must_use]
    pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
        Self::new(r, g, b, 255)
    }

    /// Yellow color (for highlighting)
    #[must_use]
    pub const fn yellow() -> Self {
        Self::rgb(255, 255, 0)
    }

    /// 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, 255, 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)
    }

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

    /// Create 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
        }
    }
}

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

/// An annotation to add to a PDF
#[derive(Debug, Clone, TypedBuilder)]
pub struct Annotation {
    /// Type of annotation
    pub annotation_type: AnnotationType,

    /// Page number (1-indexed)
    pub page: u32,

    /// Bounding rectangle
    pub rect: Rect,

    /// Annotation color
    #[builder(default)]
    pub color: Color,

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

    /// Note contents (for sticky notes, comments)
    #[builder(default, setter(into, strip_option))]
    pub contents: Option<String>,

    /// Author name
    #[builder(default, setter(into, strip_option))]
    pub author: Option<String>,

    /// Subject/title
    #[builder(default, setter(into, strip_option))]
    pub subject: Option<String>,

    /// Text for `FreeText` annotations
    #[builder(default, setter(into, strip_option))]
    pub text: Option<String>,

    /// Font size for `FreeText` annotations
    #[builder(default = 12.0)]
    pub font_size: f32,

    /// Points for line/ink annotations (pairs of x,y coordinates)
    #[builder(default)]
    pub points: Vec<(f32, f32)>,
}

/// Information about an existing annotation
#[derive(Debug, Clone)]
pub struct AnnotationInfo {
    /// Type of annotation
    pub annotation_type: AnnotationType,
    /// Page number (1-indexed)
    pub page: u32,
    /// Bounding rectangle
    pub rect: Rect,
    /// Annotation color
    pub color: Color,
    /// Opacity
    pub opacity: f32,
    /// Note contents
    pub contents: Option<String>,
    /// Author
    pub author: Option<String>,
}

/// Add annotations to a PDF document.
///
/// # Arguments
/// * `pdf_data` - The input PDF data
/// * `annotations` - The annotations to add
///
/// # Returns
/// The modified PDF data with annotations.
///
/// # Errors
///
/// Returns an error if the annotations cannot be added to the PDF.
pub fn add_annotations(pdf_data: &[u8], annotations: &[Annotation]) -> Result<Vec<u8>> {
    if annotations.is_empty() {
        return Ok(pdf_data.to_vec());
    }

    // Convert to FFI format
    let annotation_defs: Vec<printwell_sys::AnnotationDef> = annotations
        .iter()
        .map(|a| printwell_sys::AnnotationDef {
            annotation_type: a.annotation_type.to_pdfium_type(),
            page: i32::try_from(a.page).unwrap_or(i32::MAX),
            x: a.rect.x,
            y: a.rect.y,
            width: a.rect.width,
            height: a.rect.height,
            color: a.color.to_rgba(),
            opacity: a.opacity,
            contents: a.contents.clone().unwrap_or_default(),
            author: a.author.clone().unwrap_or_default(),
            text: a.text.clone().unwrap_or_default(),
            font_size: a.font_size,
        })
        .collect();

    // Call FFI function
    let result =
        printwell_sys::ffi::pdf_add_annotations(pdf_data, &annotation_defs).map_err(|e| {
            crate::AnnotationError::Operation(format!("Failed to add annotations: {e}"))
        })?;

    Ok(result)
}

/// List annotations in a PDF document.
///
/// # Arguments
/// * `pdf_data` - The input PDF data
///
/// # Returns
/// A list of annotations found in the document.
///
/// # Errors
///
/// Returns an error if the annotations cannot be listed from the PDF.
pub fn list_annotations(pdf_data: &[u8]) -> Result<Vec<AnnotationInfo>> {
    let annotation_defs = printwell_sys::ffi::pdf_list_annotations(pdf_data).map_err(|e| {
        crate::AnnotationError::Operation(format!("Failed to list annotations: {e}"))
    })?;

    let annotations = annotation_defs
        .iter()
        .filter_map(|a| {
            let annotation_type = AnnotationType::from_pdfium_type(a.annotation_type)?;
            Some(AnnotationInfo {
                annotation_type,
                page: u32::try_from(a.page).unwrap_or(0),
                rect: Rect::new(a.x, a.y, a.width, a.height),
                color: Color::new(
                    ((a.color >> 24) & 0xFF) as u8,
                    ((a.color >> 16) & 0xFF) as u8,
                    ((a.color >> 8) & 0xFF) as u8,
                    (a.color & 0xFF) as u8,
                ),
                opacity: a.opacity,
                contents: if a.contents.is_empty() {
                    None
                } else {
                    Some(a.contents.clone())
                },
                author: if a.author.is_empty() {
                    None
                } else {
                    Some(a.author.clone())
                },
            })
        })
        .collect();

    Ok(annotations)
}

/// Remove annotations from a PDF document.
///
/// # Arguments
/// * `pdf_data` - The input PDF data
/// * `page` - Optional page number to filter (None = all pages)
/// * `annotation_types` - Optional types to remove (None = all types)
///
/// # Returns
/// The modified PDF data with annotations removed.
///
/// # Errors
///
/// Returns an error if the annotations cannot be removed from the PDF.
pub fn remove_annotations(
    pdf_data: &[u8],
    page: Option<u32>,
    annotation_types: Option<&[AnnotationType]>,
) -> Result<Vec<u8>> {
    let page_filter: i32 = page.map_or(-1, |p| i32::try_from(p).unwrap_or(i32::MAX));
    let type_filter: Vec<i32> = annotation_types
        .map(|types| types.iter().map(AnnotationType::to_pdfium_type).collect())
        .unwrap_or_default();

    let result = printwell_sys::ffi::pdf_remove_annotations(pdf_data, page_filter, &type_filter)
        .map_err(|e| {
            crate::AnnotationError::Operation(format!("Failed to remove annotations: {e}"))
        })?;

    Ok(result)
}

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

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

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

    #[test]
    fn test_annotation_type_conversion() {
        let types = [
            AnnotationType::Highlight,
            AnnotationType::Underline,
            AnnotationType::Text,
            AnnotationType::FreeText,
        ];

        for t in &types {
            let pdfium = t.to_pdfium_type();
            let back = AnnotationType::from_pdfium_type(pdfium);
            assert_eq!(back, Some(*t));
        }
    }
}