printwell-pdf 0.1.6

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
//! PDF digital signature support (`PAdES`).
//!
//! This module provides functionality for digitally signing PDF documents
//! using `PAdES` (PDF Advanced Electronic Signatures) standard.
//!
//! **Note:** This feature requires a commercial license.
//! Purchase at: <https://printwell.dev/pricing>

use crate::{Result, SigningError};
use std::path::Path;
use typed_builder::TypedBuilder;

/// `PAdES` signature level
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SignatureLevel {
    /// Basic signature (PAdES-B)
    #[default]
    PadesB,
    /// With timestamp (PAdES-T)
    PadesT,
    /// Long-term validation (PAdES-LT)
    PadesLT,
    /// Long-term archival (PAdES-LTA)
    PadesLTA,
}

impl SignatureLevel {
    /// Get string representation
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::PadesB => "B",
            Self::PadesT => "T",
            Self::PadesLT => "LT",
            Self::PadesLTA => "LTA",
        }
    }
}

/// MDP (Modification Detection and Prevention) permission level for certification signatures
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum MdpPermissions {
    /// No changes allowed after certification
    NoChanges = 1,
    /// Only form filling and signing allowed
    #[default]
    FormFillingAndSigning = 2,
    /// Form filling, signing, and annotations allowed
    FormFillingSigningAndAnnotations = 3,
}

impl MdpPermissions {
    /// Get the numeric value for PDF
    #[must_use]
    pub const fn as_u32(&self) -> u32 {
        *self as u32
    }

    /// Get string representation
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::NoChanges => "no-changes",
            Self::FormFillingAndSigning => "form-filling",
            Self::FormFillingSigningAndAnnotations => "annotations",
        }
    }

    /// Parse from string (CLI argument)
    #[must_use]
    pub fn parse_arg(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "1" | "no-changes" | "none" => Some(Self::NoChanges),
            "2" | "form-filling" | "forms" => Some(Self::FormFillingAndSigning),
            "3" | "annotations" | "annots" => Some(Self::FormFillingSigningAndAnnotations),
            _ => None,
        }
    }
}

/// Certificate for signing
pub struct SigningCertificate {
    _private: (),
}

impl SigningCertificate {
    /// Load from PKCS#12 (.p12/.pfx) data
    ///
    /// # Errors
    ///
    /// Always returns an error as this feature requires a commercial license.
    pub fn from_pkcs12(_data: &[u8], _password: &str) -> Result<Self> {
        Err(SigningError::RequiresLicense.into())
    }

    /// Load from PKCS#12 file path
    ///
    /// # Errors
    ///
    /// Always returns an error as this feature requires a commercial license.
    pub fn from_pkcs12_file(_path: impl AsRef<Path>, _password: &str) -> Result<Self> {
        Err(SigningError::RequiresLicense.into())
    }

    /// Get the subject common name (CN)
    #[must_use]
    pub const fn subject_common_name(&self) -> Option<String> {
        None
    }

    /// Get the full subject name
    #[must_use]
    pub const fn subject_name(&self) -> String {
        String::new()
    }

    /// Get the issuer name
    #[must_use]
    pub const fn issuer_name(&self) -> String {
        String::new()
    }

    /// Get certificate serial number as hex
    #[must_use]
    pub const fn serial_number_hex(&self) -> String {
        String::new()
    }
}

/// Signing options
#[derive(Debug, Clone, TypedBuilder)]
#[builder(field_defaults(default, setter(into)))]
pub struct SigningOptions {
    /// Reason for signing
    #[builder(default)]
    pub reason: Option<String>,
    /// Location of signing
    #[builder(default)]
    pub location: Option<String>,
    /// Contact information
    #[builder(default)]
    pub contact_info: Option<String>,
    /// Signature level
    #[builder(default)]
    pub signature_level: SignatureLevel,
    /// Timestamp server URL (required for T, LT, LTA levels)
    #[builder(default)]
    pub timestamp_url: Option<String>,
    /// Field name for the signature
    #[builder(default = "Signature".to_string())]
    pub field_name: String,
    /// Include certificate chain in signature
    #[builder(default = true)]
    pub include_chain: bool,
    /// Create a certification signature (first signature that certifies the document)
    #[builder(default = false)]
    pub certify: bool,
    /// MDP permissions for certification signatures (only used when certify=true)
    #[builder(default)]
    pub mdp_permissions: MdpPermissions,
}

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

/// Visible signature appearance
#[derive(Debug, Clone, TypedBuilder)]
#[builder(field_defaults(default, setter(into)))]
pub struct SignatureAppearance {
    /// Page number (1-based, 0 = last page)
    #[builder(default = 1)]
    pub page: u32,
    /// X coordinate in points
    #[builder(default = 50.0)]
    pub x: f64,
    /// Y coordinate in points
    #[builder(default = 50.0)]
    pub y: f64,
    /// Width in points
    #[builder(default = 200.0)]
    pub width: f64,
    /// Height in points
    #[builder(default = 75.0)]
    pub height: f64,
    /// Show signer name
    #[builder(default = true)]
    pub show_name: bool,
    /// Show signing date
    #[builder(default = true)]
    pub show_date: bool,
    /// Show reason
    #[builder(default = true)]
    pub show_reason: bool,
    /// Background image data
    #[builder(default)]
    pub background_image: Option<Vec<u8>>,
}

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

/// Signed PDF document
pub struct SignedPdf {
    data: Vec<u8>,
}

impl SignedPdf {
    /// Get PDF data as bytes
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        &self.data
    }

    /// Consume and return PDF data
    #[must_use]
    pub fn into_bytes(self) -> Vec<u8> {
        self.data
    }

    /// Write to file
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be written.
    pub fn write_to_file(&self, path: impl AsRef<Path>) -> Result<()> {
        std::fs::write(path, &self.data)?;
        Ok(())
    }
}

/// Sign a PDF document with an invisible signature.
///
/// **Note:** This feature requires a commercial license.
///
/// # Errors
///
/// Always returns an error as this feature requires a commercial license.
pub fn sign_pdf(
    _pdf_data: &[u8],
    _certificate: &SigningCertificate,
    _options: &SigningOptions,
) -> Result<SignedPdf> {
    Err(SigningError::RequiresLicense.into())
}

/// Sign a PDF document with a visible signature.
///
/// **Note:** This feature requires a commercial license.
///
/// # Errors
///
/// Always returns an error as this feature requires a commercial license.
pub fn sign_pdf_visible(
    _pdf_data: &[u8],
    _certificate: &SigningCertificate,
    _options: &SigningOptions,
    _appearance: &SignatureAppearance,
) -> Result<SignedPdf> {
    Err(SigningError::RequiresLicense.into())
}

/// Document signature validity
#[derive(Debug, Clone, Copy, Default)]
pub struct DocumentValidity {
    /// Whether signature is valid
    pub is_valid: bool,
    /// Whether signature covers whole document
    pub covers_whole_document: bool,
}

/// Certificate validity flags
#[derive(Debug, Clone, Copy, Default)]
pub struct CertificateValidity {
    /// Whether certificate is within validity period
    pub time_valid: bool,
    /// Whether certificate has proper key usage
    pub usage_valid: bool,
}

/// Signature validation status flags
#[derive(Debug, Clone, Copy, Default)]
pub struct SignatureStatus {
    /// Document signature validity
    pub document: DocumentValidity,
    /// Certificate validity
    pub certificate: CertificateValidity,
}

/// Signature verification result
#[derive(Debug)]
pub struct SignatureVerification {
    /// Signer name
    pub signer_name: String,
    /// Signing time
    pub signing_time: Option<String>,
    /// Reason for signing
    pub reason: Option<String>,
    /// Location
    pub location: Option<String>,
    /// Validation status flags
    pub status: SignatureStatus,
    /// Certificate validation warnings
    pub cert_warnings: Vec<String>,
    /// Verification error message (if any)
    pub error: Option<String>,
}

impl From<printwell_sys::SignatureInfo> for SignatureVerification {
    fn from(info: printwell_sys::SignatureInfo) -> Self {
        Self {
            signer_name: info.signer_name,
            signing_time: if info.signing_time.is_empty() {
                None
            } else {
                Some(info.signing_time)
            },
            reason: if info.reason.is_empty() {
                None
            } else {
                Some(info.reason)
            },
            location: if info.location.is_empty() {
                None
            } else {
                Some(info.location)
            },
            status: SignatureStatus {
                document: DocumentValidity {
                    is_valid: info.is_valid,
                    covers_whole_document: info.covers_whole_document,
                },
                certificate: CertificateValidity {
                    // Default values for fields not in SignatureInfo
                    time_valid: true,
                    usage_valid: true,
                },
            },
            cert_warnings: Vec::new(),
            error: None,
        }
    }
}

/// Extracted signature data from a PDF
#[derive(Debug)]
pub struct ExtractedSignature {
    /// CMS/PKCS#7 signature contents (DER encoded)
    pub contents: Vec<u8>,
    /// Byte range
    pub byte_range: Vec<i64>,
    /// `SubFilter` (e.g., "adbe.pkcs7.detached")
    pub sub_filter: String,
    /// Reason for signing
    pub reason: Option<String>,
    /// Location
    pub location: Option<String>,
    /// Signing time
    pub signing_time: Option<String>,
    /// Signer name
    pub signer_name: Option<String>,
}

/// Extract all signatures from a PDF.
///
/// **Note:** This feature requires a commercial license.
///
/// # Errors
///
/// Always returns an error as this feature requires a commercial license.
pub fn extract_signatures(_pdf_data: &[u8]) -> Result<Vec<ExtractedSignature>> {
    Err(SigningError::RequiresLicense.into())
}

/// Verify all signatures in a PDF.
///
/// **Note:** This feature requires a commercial license.
///
/// # Errors
///
/// Always returns an error as this feature requires a commercial license.
pub fn verify_signatures(_pdf_data: &[u8]) -> Result<Vec<SignatureVerification>> {
    Err(SigningError::RequiresLicense.into())
}

/// Verify all signatures in a PDF with custom trust store.
///
/// **Note:** This feature requires a commercial license.
///
/// # Errors
///
/// Always returns an error as this feature requires a commercial license.
pub fn verify_signatures_with_trust(
    _pdf_data: &[u8],
    _trust_store: Option<&crate::crypto::TrustStore>,
) -> Result<Vec<SignatureVerification>> {
    Err(SigningError::RequiresLicense.into())
}

/// Information about an existing signature field
#[derive(Debug, Clone)]
pub struct SignatureFieldInfo {
    /// Field name
    pub name: String,
    /// Page number (1-based)
    pub page: u32,
    /// X coordinate in points
    pub x: f64,
    /// Y coordinate in points
    pub y: f64,
    /// Width in points
    pub width: f64,
    /// Height in points
    pub height: f64,
    /// Whether the field is already signed
    pub is_signed: bool,
}

/// List all signature fields in a PDF.
///
/// **Note:** This feature requires a commercial license.
///
/// # Errors
///
/// Always returns an error as this feature requires a commercial license.
pub fn list_signature_fields(_pdf_data: &[u8]) -> Result<Vec<SignatureFieldInfo>> {
    Err(SigningError::RequiresLicense.into())
}

/// Sign into an existing signature field.
///
/// **Note:** This feature requires a commercial license.
///
/// # Errors
///
/// Always returns an error as this feature requires a commercial license.
pub fn sign_pdf_field(
    _pdf_data: &[u8],
    _field_name: &str,
    _certificate: &SigningCertificate,
    _options: &SigningOptions,
) -> Result<SignedPdf> {
    Err(SigningError::RequiresLicense.into())
}

/// MDP (Modification Detection and Prevention) permission level
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum MdpPermission {
    /// No changes allowed after signing
    NoChanges = 1,
    /// Form filling and signing allowed
    #[default]
    FormFillAndSign = 2,
    /// Form filling, signing, and annotations allowed
    AnnotationsAllowed = 3,
}

/// Create a certification (MDP) signature.
///
/// **Note:** This feature requires a commercial license.
///
/// # Errors
///
/// Always returns an error as this feature requires a commercial license.
pub fn certify_pdf(
    _pdf_data: &[u8],
    _certificate: &SigningCertificate,
    _options: &SigningOptions,
    _permission: MdpPermission,
) -> Result<SignedPdf> {
    Err(SigningError::RequiresLicense.into())
}