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
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
//! PDF form field support (`AcroForms`).
//!
//! This module provides functionality for adding interactive form fields
//! to PDF documents using `PDFium` via FFI.
//!
//! **Note:** This feature requires a commercial license.
//! Purchase at: <https://printwell.dev/pricing>

use crate::{FormError, Result};
use typed_builder::TypedBuilder;

/// Default values for form field creation
#[derive(Debug, Clone, TypedBuilder)]
#[builder(field_defaults(default, setter(into)))]
pub struct FormFieldDefaults {
    /// Default font size for text fields
    #[builder(default = 12.0)]
    pub font_size: f64,
    /// Default font name for text fields
    #[builder(default = "Helvetica".to_string())]
    pub font_name: String,
    /// Minimum width for form fields
    #[builder(default = 50.0)]
    pub min_width: f64,
    /// Minimum height for form fields
    #[builder(default = 15.0)]
    pub min_height: f64,
    /// Default export value for checkboxes
    #[builder(default = "Yes".to_string())]
    pub checkbox_export_value: String,
}

impl Default for FormFieldDefaults {
    fn default() -> Self {
        Self::builder().build()
    }
}

/// Rectangle specification for form fields
#[derive(Debug, Clone, Copy, Default)]
pub struct Rect {
    /// X coordinate in PDF points
    pub x: f64,
    /// Y coordinate in PDF points
    pub y: f64,
    /// Width in PDF points
    pub width: f64,
    /// Height in PDF points
    pub height: f64,
}

/// Text input behavior flags
#[derive(Debug, Clone, Copy, Default, TypedBuilder)]
#[builder(field_defaults(default))]
pub struct InputBehavior {
    /// Allow multiple lines
    pub multiline: bool,
    /// Password field (mask input)
    pub password: bool,
}

/// Field constraint flags
#[derive(Debug, Clone, Copy, Default, TypedBuilder)]
#[builder(field_defaults(default))]
pub struct FieldConstraints {
    /// Required field
    pub required: bool,
    /// Read-only field
    pub read_only: bool,
}

/// Text field flags combining behavior and constraints
#[derive(Debug, Clone, Copy, Default, TypedBuilder)]
#[builder(field_defaults(default))]
pub struct TextFieldFlags {
    /// Input behavior flags
    pub behavior: InputBehavior,
    /// Field constraint flags
    pub constraints: FieldConstraints,
}

/// Text field definition
#[derive(Debug, Clone, TypedBuilder)]
#[builder(field_defaults(default, setter(into)))]
pub struct TextField {
    /// Field name
    pub name: String,
    /// Page number (1-based)
    pub page: u32,
    /// Field rectangle
    pub rect: Rect,
    /// Default value
    #[builder(default)]
    pub default_value: Option<String>,
    /// Maximum character length
    #[builder(default)]
    pub max_length: Option<u32>,
    /// Field behavior flags
    #[builder(default)]
    pub flags: TextFieldFlags,
    /// Font size
    #[builder(default = 12.0)]
    pub font_size: f64,
    /// Font name
    #[builder(default = "Helvetica".into())]
    pub font_name: String,
}

impl TextField {
    /// Convert to FFI representation
    #[must_use]
    pub fn to_ffi(&self) -> printwell_sys::TextFieldDef {
        printwell_sys::TextFieldDef {
            name: self.name.clone(),
            page: self.page,
            x: self.rect.x,
            y: self.rect.y,
            width: self.rect.width,
            height: self.rect.height,
            default_value: self.default_value.clone().unwrap_or_default(),
            max_length: self.max_length.unwrap_or(0),
            multiline: self.flags.behavior.multiline,
            password: self.flags.behavior.password,
            required: self.flags.constraints.required,
            read_only: self.flags.constraints.read_only,
            font_size: self.font_size,
            font_name: self.font_name.clone(),
        }
    }
}

/// Checkbox definition
#[derive(Debug, Clone, TypedBuilder)]
#[builder(field_defaults(default, setter(into)))]
pub struct Checkbox {
    /// Field name
    pub name: String,
    /// Page number (1-based)
    pub page: u32,
    /// Field rectangle
    pub rect: Rect,
    /// Initial checked state
    #[builder(default = false)]
    pub checked: bool,
    /// Export value when checked
    #[builder(default = "Yes".into())]
    pub export_value: String,
}

impl Checkbox {
    /// Convert to FFI representation
    #[must_use]
    pub fn to_ffi(&self) -> printwell_sys::CheckboxDef {
        printwell_sys::CheckboxDef {
            name: self.name.clone(),
            page: self.page,
            x: self.rect.x,
            y: self.rect.y,
            size: self.rect.width.min(self.rect.height), // Use smaller dimension as size
            checked: self.checked,
            export_value: self.export_value.clone(),
        }
    }
}

/// Dropdown (combo box) definition
#[derive(Debug, Clone, TypedBuilder)]
#[builder(field_defaults(default, setter(into)))]
pub struct Dropdown {
    /// Field name
    pub name: String,
    /// Page number (1-based)
    pub page: u32,
    /// Field rectangle
    pub rect: Rect,
    /// Available options
    #[builder(default)]
    pub options: Vec<String>,
    /// Selected index (None for no selection)
    #[builder(default)]
    pub selected_index: Option<usize>,
    /// Allow custom input
    #[builder(default = false)]
    pub editable: bool,
}

impl Dropdown {
    /// Convert to FFI representation
    #[must_use]
    pub fn to_ffi(&self) -> printwell_sys::DropdownDef {
        printwell_sys::DropdownDef {
            name: self.name.clone(),
            page: self.page,
            x: self.rect.x,
            y: self.rect.y,
            width: self.rect.width,
            height: self.rect.height,
            options: self.options.clone(),
            selected_index: self
                .selected_index
                .map_or(-1, |i| i32::try_from(i).unwrap_or(i32::MAX)),
            editable: self.editable,
        }
    }
}

/// Signature field definition
#[derive(Debug, Clone, TypedBuilder)]
#[builder(field_defaults(default, setter(into)))]
pub struct SignatureField {
    /// Field name
    pub name: String,
    /// Page number (1-based)
    pub page: u32,
    /// Field rectangle
    pub rect: Rect,
}

impl SignatureField {
    /// Convert to FFI representation
    #[must_use]
    pub fn to_ffi(&self) -> printwell_sys::SignatureFieldDef {
        printwell_sys::SignatureFieldDef {
            name: self.name.clone(),
            page: self.page,
            x: self.rect.x,
            y: self.rect.y,
            width: self.rect.width,
            height: self.rect.height,
        }
    }
}

/// Form builder for adding multiple fields
pub struct FormBuilder {
    _private: (),
}

impl FormBuilder {
    /// Create a new form builder
    ///
    /// # Errors
    ///
    /// Always returns an error as this feature requires a commercial license.
    pub fn new(_pdf_data: &[u8]) -> Result<Self> {
        Err(FormError::RequiresLicense.into())
    }

    /// Add a text field
    ///
    /// # Errors
    ///
    /// Always returns an error as this feature requires a commercial license.
    pub fn add_text_field(&mut self, _field: TextField) -> Result<&mut Self> {
        Err(FormError::RequiresLicense.into())
    }

    /// Add a checkbox
    ///
    /// # Errors
    ///
    /// Always returns an error as this feature requires a commercial license.
    pub fn add_checkbox(&mut self, _field: Checkbox) -> Result<&mut Self> {
        Err(FormError::RequiresLicense.into())
    }

    /// Add a dropdown
    ///
    /// # Errors
    ///
    /// Always returns an error as this feature requires a commercial license.
    pub fn add_dropdown(&mut self, _field: Dropdown) -> Result<&mut Self> {
        Err(FormError::RequiresLicense.into())
    }

    /// Add a signature field
    ///
    /// # Errors
    ///
    /// Always returns an error as this feature requires a commercial license.
    pub fn add_signature_field(&mut self, _field: SignatureField) -> Result<&mut Self> {
        Err(FormError::RequiresLicense.into())
    }

    /// Build and return the PDF with forms
    ///
    /// # Errors
    ///
    /// Always returns an error as this feature requires a commercial license.
    pub fn build(self) -> Result<Vec<u8>> {
        Err(FormError::RequiresLicense.into())
    }
}

/// Form field interaction state
#[derive(Debug, Clone, Copy, Default)]
pub struct FieldInteractionState {
    /// Whether the field is disabled
    pub disabled: bool,
    /// Whether the field is checked (checkbox/radio)
    pub checked: bool,
}

/// Form field constraint state
#[derive(Debug, Clone, Copy, Default)]
pub struct FieldConstraintState {
    /// Required field
    pub required: bool,
    /// Read-only field
    pub readonly: bool,
}

/// Form field input type state
#[derive(Debug, Clone, Copy, Default)]
pub struct FieldInputState {
    /// Allow multiple lines (text fields)
    pub multiline: bool,
    /// Password field (text fields)
    pub password: bool,
}

/// Form field state flags
#[derive(Debug, Clone, Copy, Default)]
pub struct FormFieldState {
    /// Interaction state
    pub interaction: FieldInteractionState,
    /// Constraint state
    pub constraints: FieldConstraintState,
    /// Input type state
    pub input: FieldInputState,
}

/// Detected form element from HTML
#[derive(Debug, Clone, Default)]
pub struct DetectedFormElement {
    /// Element type (e.g., "text", "checkbox", "radio", "select", "signature")
    pub element_type: String,
    /// Element ID
    pub id: String,
    /// Field name
    pub name: String,
    /// Page number
    pub page: u32,
    /// X coordinate
    pub x: f64,
    /// Y coordinate
    pub y: f64,
    /// Width
    pub width: f64,
    /// Height
    pub height: f64,
    /// Default value
    pub default_value: String,
    /// Placeholder text
    pub placeholder: String,
    /// Field state flags
    pub state: FormFieldState,
    /// Export value
    pub export_value: String,
    /// Radio button group name
    pub radio_group: String,
    /// Dropdown options
    pub options: Vec<String>,
    /// Selected index
    pub selected_index: i32,
    /// Max length
    pub max_length: u32,
    /// Font size
    pub font_size: f64,
}

/// Form element type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FormElementType {
    /// Text input field
    #[default]
    TextField,
    /// Checkbox
    Checkbox,
    /// Radio button
    RadioButton,
    /// Dropdown/select
    Dropdown,
    /// Signature field
    Signature,
}

/// Apply detected form elements to a PDF.
///
/// **Note:** This feature requires a commercial license.
///
/// # Errors
///
/// Always returns an error as this feature requires a commercial license.
pub fn apply_detected_forms(
    _pdf_data: &[u8],
    _elements: &[DetectedFormElement],
) -> Result<Vec<u8>> {
    Err(FormError::RequiresLicense.into())
}

/// Apply detected form elements with custom defaults.
///
/// **Note:** This feature requires a commercial license.
///
/// # Errors
///
/// Always returns an error as this feature requires a commercial license.
pub fn apply_detected_forms_with_defaults(
    _pdf_data: &[u8],
    _elements: &[DetectedFormElement],
    _defaults: &FormFieldDefaults,
) -> Result<Vec<u8>> {
    Err(FormError::RequiresLicense.into())
}

/// Validation rule for a form field
#[derive(Debug, Clone, Default)]
pub struct ValidationRule {
    /// Field name pattern (supports wildcards)
    pub field_name: String,
    /// Field is required
    pub required: bool,
    /// Minimum value (for numeric fields)
    pub min_value: Option<f64>,
    /// Maximum value (for numeric fields)
    pub max_value: Option<f64>,
    /// Minimum length (for text fields)
    pub min_length: Option<usize>,
    /// Maximum length (for text fields)
    pub max_length: Option<usize>,
    /// Regex pattern
    pub pattern: Option<String>,
    /// Custom error message
    pub error_message: Option<String>,
    /// Error message for required validation
    pub required_message: Option<String>,
    /// Error message for pattern validation
    pub pattern_message: Option<String>,
    /// Error message for length validation
    pub length_message: Option<String>,
    /// Error message for value validation
    pub value_message: Option<String>,
    /// List of allowed values
    pub allowed_values: Option<Vec<String>>,
}

/// Validation result for a single field
#[derive(Debug, Clone)]
pub struct ValidationResult {
    /// Field name
    pub field_name: String,
    /// Whether validation passed
    pub is_valid: bool,
    /// List of validation errors
    pub errors: Vec<String>,
    /// Field value that was validated
    pub value: String,
}

/// Summary of validation results
#[derive(Debug, Clone)]
pub struct ValidationSummary {
    /// All validation results
    pub results: Vec<ValidationResult>,
    /// Overall validity
    pub is_valid: bool,
    /// Total number of errors
    pub error_count: usize,
    /// Total number of fields validated
    pub total_fields: usize,
    /// Number of valid fields
    pub valid_count: usize,
    /// Number of invalid fields
    pub invalid_count: usize,
    /// Whether all fields are valid
    pub all_valid: bool,
}

/// Validate form fields against rules.
///
/// **Note:** This feature requires a commercial license.
#[must_use]
pub const fn validate_form_fields(
    _elements: &[DetectedFormElement],
    _rules: &[ValidationRule],
) -> ValidationSummary {
    ValidationSummary {
        results: vec![],
        is_valid: false,
        error_count: 1,
        total_fields: 0,
        valid_count: 0,
        invalid_count: 0,
        all_valid: false,
    }
}

/// Validate a single form field.
///
/// **Note:** This feature requires a commercial license.
#[must_use]
pub fn validate_field(_element: &DetectedFormElement, _rule: &ValidationRule) -> ValidationResult {
    ValidationResult {
        field_name: String::new(),
        is_valid: false,
        errors: vec!["PDF form manipulation requires a commercial license. Purchase at: https://printwell.dev/pricing".to_string()],
        value: String::new(),
    }
}

/// Common validation patterns for form fields.
pub mod patterns {
    /// Email address pattern (RFC 5322 simplified)
    pub const EMAIL: &str = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$";
    /// URL pattern (http/https)
    pub const URL: &str = r"^https?://[^\s/$.?#].[^\s]*$";
    /// Phone number (international, flexible)
    pub const PHONE: &str = r"^\+?[0-9\s\-().]{7,}$";
    /// US phone number
    pub const US_PHONE: &str = r"^\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}$";
    /// US ZIP code (5 or 9 digits)
    pub const US_ZIP: &str = r"^[0-9]{5}(-[0-9]{4})?$";
    /// Positive integer
    pub const POSITIVE_INTEGER: &str = r"^[1-9][0-9]*$";
    /// Non-negative integer
    pub const NON_NEGATIVE_INTEGER: &str = r"^(0|[1-9][0-9]*)$";
    /// Decimal number
    pub const DECIMAL: &str = r"^-?[0-9]+(\.[0-9]+)?$";
    /// Date in ISO format (YYYY-MM-DD)
    pub const DATE_ISO: &str = r"^[0-9]{4}-[0-9]{2}-[0-9]{2}$";
    /// Date in US format (MM/DD/YYYY)
    pub const DATE_US: &str = r"^[0-9]{2}/[0-9]{2}/[0-9]{4}$";
    /// Alphabetic only
    pub const ALPHA: &str = r"^[a-zA-Z]+$";
    /// Alphanumeric only
    pub const ALPHANUMERIC: &str = r"^[a-zA-Z0-9]+$";
    /// No whitespace
    pub const NO_WHITESPACE: &str = r"^\S+$";
    /// Credit card number (basic, 13-19 digits)
    pub const CREDIT_CARD: &str = r"^[0-9]{13,19}$";
    /// Social Security Number (XXX-XX-XXXX)
    pub const SSN: &str = r"^[0-9]{3}-[0-9]{2}-[0-9]{4}$";
}